import React, { useState } from "react";
import UploadFile from "./uploadFile";
import { IFile } from "../interface";
import { QueryClientProvider } from "react-query";
import { DefaultExtensionType, defaultStyles, FileIcon } from "react-file-icon";
import Pagination from "../extra/pagination";
import useGetFiles from "../hooks/useGetFiles";
import { queryClient } from "..";
import { configSrore } from "../configSrore";
import { FillArrow } from "../svg";
import { FaDateFromTimestamp } from "../utils";
import RenameFile from "./renameFile";
import RenderIf from "../extra/renderIf";
import DeleteFile from "./deleteFile";

const getColor = (type: string) => {
  if (
    type === "png"
        || type.includes("jpeg")
        || type.includes("jpg")
        || type.includes("image")
  ) {
    return "#F47C7C";
  }
  if (type.includes("pdf")) return "#FF4949";
  if (type.includes("txt")) return "#36AE7C";
  if (type.includes("audio") || type.includes("mp3")) return "#646FD4";
  if (type.includes("mp4")) return "#FF5F00";
  return "#4C3575";
};

const fileTablePageSize = 5;

const FileManager = () => {
  const [page, setPage] = useState<number>(0);
  const { data: files, refetch } = useGetFiles(configSrore.userGroupHash, page, fileTablePageSize);
  //   const [search, setSearch] = useState<string>("");
  const [sortByName, setSortByName] = useState(-1);

  //   const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  //     setSearch(event.target.value);
  //   };

  const searchlist = files?.list?.sort((a: any, b: any) => {
    if (a.name < b.name) {
      return sortByName;
    }
    if (a.name > b.name) {
      return -1 * sortByName;
    }
    return 0;
  });

  return (
    <QueryClientProvider client={queryClient}>
      <div className="file-management-wrapper h-full w-full p-5" dir="rtl">
        <div className="flex h-fit flex-wrap items-center">
          <h3 className="title">مدیریت فایل ها</h3>
          <div className="flex items-center mr-auto">
            <div className="relative ml-[14px] min-w-[240px]">
              {/* <span className="absolute inset-y-0 right-3 flex items-center">
                <SearchIcon className="w-4 h-4 fill-base-200" />
              </span>
              <input
                type="search"
                className="w-full py-[7px] pr-9 pl-2 bg-transparent rounded-[4px] focus:outline-none border-2 border-gray-300 font-yekan-regular font-normal text-xs text-base-200 placeholder:text-gray-300 leading-3"
                placeholder="جست و جو ..."
                autoComplete="off"
                onChange={handleChange}
              /> */}
            </div>
            <UploadFile refetch={refetch} page={page} userGroupHash={configSrore.userGroupHash} />
          </div>
        </div>
        <div
          className="overflow-x-auto w-full bg-white rounded-[4px] mt-4 min-h-[320px] shadow-[0px_2px_3px_rgba(0,0,0,0.07)]"
        >
          <table className="custom-table user-table table-fixed w-full">
            <thead>
              <tr>
                <th className="sticky top-0 bg-white z-10">
                  <div className="flex">
                    <span className="block">نام فایل</span>

                    <div className="flex flex-col mr-[11px]">
                      <button
                        className="btn btn-up p-0 bg-transparent hover:bg-transparent"
                        onClick={() => {
                          return setSortByName(-1);
                        }}
                      >
                        <FillArrow className="w-[9px] h-[9px] fill-base-100" />
                      </button>
                      <button
                        className="btn btn-up p-0 bg-transparent hover:bg-transparent"
                        onClick={() => {
                          return setSortByName(1);
                        }}
                      >
                        <FillArrow className="w-[9px] h-[9px] fill-base-100 rotate-180" />
                      </button>
                    </div>
                  </div>
                </th>
                <th className="sticky top-0 bg-white z-10">
                  <div className="flex">
                    <span className="block">تاریخ آپلود</span>
                  </div>
                </th>
                <th className="sticky top-0 bg-white z-10">حجم</th>
                <th className="sticky top-0 bg-white z-10">عملیات</th>
              </tr>
            </thead>
            <tbody>
              {searchlist?.map((item: IFile) => {
                return (
                  <tr
                    key={JSON.stringify(item)}
                    className="hover:bg-sky-100 hover:cursor-pointer"
                    onClick={() => {
                      return configSrore.onSelectItem?.(item);
                    }}
                  >
                    <td>
                      <div className="flex items-center">
                        <div className="w-8 h-8 inline-block">
                          <FileIcon
                            extension={item.extension}
                            {...defaultStyles[
                               item.extension as unknown as DefaultExtensionType
                            ]}
                            glyphColor={getColor(item.extension || "")}
                            labelColor={getColor(item.extension || "")}
                          />
                        </div>
                        <span className="block text-xs font-yekan-regular font-normal text-base-200 mr-[10px] truncate">
                          {`${item.name || ""}.${item.extension ? item.extension : ""
                          }`}
                        </span>
                      </div>
                    </td>
                    <td>
                      <span className="px-3 py-[5px] font-yekan-medium text-xs text-base-200 ">
                        {FaDateFromTimestamp(item.updated)}
                      </span>
                    </td>
                    <td>
                      <span className="px-3 py-[5px]  font-yekan-medium text-xs text-base-200 ">
                        {`${item.size} کیلوبایت`}
                      </span>
                    </td>
                    <td>
                      <div className="user-table__actions h-5 flex gap-x-[21px] justify-end">
                        <RenderIf isTrue={!!configSrore.resourceId}>
                           <>
                            <RenameFile
                                fileInfo={item}
                                page={page}
                                refetch={refetch}
                                />
                            <DeleteFile
                                resourceId={configSrore.resourceId!}
                                userGroupHash={configSrore.userGroupHash}
                                file={item}
                                page={page}
                                refetch={refetch}
                            />
                           </>
                        </RenderIf>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        <div
          dir="ltr"
          className="user-list__pagination w-full h-fit bg-cover mt-[30px] text-left"
        >
          {files && (
            <Pagination
              changePage={page}
              total={files.count}
              pageSize={fileTablePageSize}
              onChange={setPage}
            />
          )}
        </div>
      </div>
    </QueryClientProvider>

  );
};

export default FileManager;
