"use client";

import React, { useCallback, useMemo, useState } from "react";
import SearchBox, { Criterion } from "../SearchBox";
import { useTranslation } from "react-i18next";
import SearchResults, { Column } from "../SearchResults";
import EditNote from "@mui/icons-material/EditNote";
import { SalaryResult } from "@/app/api/salarys";
import { convertLocaleStringToNumber } from "@/app/utils/formatUtil"
import { Button, ButtonGroup, Stack } from "@mui/material";
import FileDownloadIcon from '@mui/icons-material/FileDownload';
import FileUploadIcon from '@mui/icons-material/FileUpload';
import { exportSalary, importSalarys } from "@/app/api/salarys/actions";
import { downloadFile } from "@/app/utils/commonUtil";
import { errorDialog, successDialog } from "../Swal/CustomAlerts";
import { MAINTAIN_SALARY } from "@/middleware";

interface Props {
  salarys: SalaryResult[];
  abilities: String[];
}

type SearchQuery = Partial<Omit<SalaryResult, "id">>;
type SearchParamNames = keyof SearchQuery;

const SalarySearch: React.FC<Props> = ({ salarys, abilities }) => {
  const { t } = useTranslation("salarys");

  const [filteredSalarys, setFilteredSalarys] = useState(salarys);
  const maintainSalary = abilities.includes(MAINTAIN_SALARY)

  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
    () => [
      { label: t("Salary"), paramName: "salary", type: "text" },
      { label: t("Salary Point"), paramName: "salaryPoint", type: "text" },
    ],
    [t, salarys],
  );

  const onReset = useCallback(() => {
    setFilteredSalarys(salarys);
  }, [salarys]);

  const onSalaryClick = useCallback((salary: SalaryResult) => {
    console.log(salary);
  }, []);

  const handleImportClick = useCallback(async (event:any) => {
    // console.log(event)
    try {

      const file = event.target.files[0];

      if (!file) {
        console.log('No file selected');
        return;
      }

      if (file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
        console.log('Invalid file format. Only XLSX files are allowed.');
        return;
      }

      const formData = new FormData();
      formData.append('multipartFileList', file);

      const response = await importSalarys(formData);

      if (response === "OK") {
        successDialog(t("Import Success"), t).then(()=>{
          window.location.reload()
        })
      }else{
        errorDialog(t("Import Fail")).then(()=>{
          window.location.reload()
        })
      }

  } catch (err) {
      console.log(err)
      return false
  }
  }, []);

  const handleExportClick = useCallback(async (event:any) => {
    // console.log(event);
    try{
      const response = await exportSalary()
      if (response) {
        downloadFile(new Uint8Array(response.blobValue), response.filename!!)
      }
    }catch(error){
      console.log(error)
    }
  }, []);

  const columns = useMemo<Column<SalaryResult>[]>(
    () => [
      // {
      //   name: "id",
      //   label: t("Details"),
      //   onClick: onSalaryClick,
      //   buttonIcon: <EditNote />,
      // },
      { name: "salaryPoint", label: t("Salary Point") },
      { name: "lowerLimit", label: t("Lower Limit") },
      { name: "upperLimit", label: t("Upper Limit") },
      { name: "hourlyRate", label: t("Hourly Rate") },
    ],
    [t, onSalaryClick],
  );

  return (
    <>
    {maintainSalary && <Stack
      direction="row"
      justifyContent="right"
      flexWrap="wrap"
      spacing={2}
    >
      <ButtonGroup variant="contained">
        <Button startIcon={<FileUploadIcon />} variant="contained" component="label">
          <input
            id='importExcel'
            type='file'
            accept='.xlsx, .csv'
            hidden
            onChange={(event) => {handleImportClick(event)}}
          />
          {t("Import Salary")}
        </Button>
        <Button startIcon={<FileDownloadIcon />} onClick={handleExportClick} component="label" variant="contained">
          {t("Export Salary")}
        </Button>
      </ButtonGroup>
    </Stack>}
      <SearchBox
        criteria={searchCriteria}
        onSearch={(query) => {
          // console.log(Number(query.salaryPoint))
          setFilteredSalarys(
            salarys.filter(
              (s) => 
                {
                  // console.log(s)
                  return (
                    ((convertLocaleStringToNumber(s.lowerLimit) <= Number(query.salary))&&
                    (convertLocaleStringToNumber(s.upperLimit) >= Number(query.salary)))||
                    (s.salaryPoint === Number(query.salaryPoint))
                  )
                }
                
            ),
          );
        }}
        onReset={onReset}
      />
      <SearchResults<SalaryResult>
        items={filteredSalarys}
        columns={columns}
      />
    </>
  );
};

export default SalarySearch;
