"use client";
import { StaffResult } from "@/app/api/staff";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import SearchBox, { Criterion } from "../SearchBox/index";
import { useTranslation } from "react-i18next";
import SearchResults, { Column } from "../SearchResults/index";
import EditNote from "@mui/icons-material/EditNote";
import DeleteIcon from "@mui/icons-material/Delete";
import { deleteStaff } from "@/app/api/staff/actions";
import { useRouter } from "next/navigation";
import { deleteDialog, successDialog } from "../Swal/CustomAlerts";
import Person from '@mui/icons-material/Person';
import { MAINTAIN_STAFF, MAINTAIN_USER } from "@/middleware";
import { TeamResult } from "@/app/api/team";
import { Grade } from "@/app/api/grades";
import { PositionResult } from "@/app/api/positions";
import { Button, Stack } from "@mui/material";
import FileDownloadIcon from '@mui/icons-material/FileDownload';
import { fetchStaffCurrentInfo } from "@/app/api/reports/actions";
import { downloadFile } from "@/app/utils/commonUtil";

interface Props {
  staff: StaffResult[];
  teams: TeamResult[]
  grades: Grade[]
  positions: PositionResult[]
  abilities: String[]
}

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

const StaffSearch: React.FC<Props> = ({ staff, teams, grades, positions, abilities }) => {
  const { t } = useTranslation();
  const [filteredStaff, setFilteredStaff] = useState(staff);
  const router = useRouter();

  const teamCombo = teams.map(t => `${t.name} - ${t.code}`)
  const gradeCombo = grades.map(g => `${g.name}`)
  const positionCombo = positions.map(p => `${p.name}`)

  const maintainUser = abilities.includes(MAINTAIN_USER)
  const maintainStaff = abilities.includes(MAINTAIN_STAFF)

  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
    () => [
      {
        label: t("Team"),
        paramName: "team",
        type: "select",
        options: teamCombo,
      },
      {
        label: t("Staff Name"),
        paramName: "name",
        type: "text",
      },
      {
        label: t("Staff ID"),
        paramName: "staffId",
        type: "text",
      },
      {
        label: t("Grade"),
        paramName: "grade",
        type: "select",
        options: gradeCombo,
      },
      {
        label: t("Current Position"),
        paramName: "currentPosition",
        type: "select",
        options: positionCombo,
      },
      {
        label: t("Active"),
        paramName: "active",
        type: "select",
        options: ["true", "false"],
      },
    ],
    [t]
  );

  const onStaffClick = useCallback(
    (staff: StaffResult) => {
      // console.log(staff);
      const id = staff.id;
      router.push(`/settings/staff/edit?id=${id}`);
    },
    [router, t]
  );

  const onUserClick = useCallback(
    (staff: StaffResult) => {
      // console.log(staff);
      router.push(`/settings/staff/user?id=${staff.userId}`);
    },
    [router, t]
  );

  const deleteClick = useCallback((staff: StaffResult) => {
    deleteDialog(async () => {
      await deleteStaff(staff.id);
      successDialog(t("Delete Success"), t);
    }, t);
  }, []);

  const handleExport = useCallback(async (ids: number[]) => {
    console.log(ids)
    const response = await fetchStaffCurrentInfo(
      {staffIds: ids}
    )
  if (response) {
      downloadFile(new Uint8Array(response.blobValue), response.filename!!)
  }
  },[filteredStaff])

  useEffect(() => {
    setFilteredStaff(staff)
  }, [staff]);

  const columns = useMemo<Column<StaffResult>[]>(
    () => [
      {
        name: "action",
        label: t("Actions"),
        onClick: onStaffClick,
        buttonIcon: <EditNote />,
        isHidden: !maintainStaff,
      },
      {
        name: "id",
        label: t("Users"),
        onClick: onUserClick,
        buttonIcon: <Person />,
        isHidden: !maintainUser,
      },
      { name: "team", label: t("Team") },
      { name: "name", label: t("Staff Name") },
      { name: "staffId", label: t("Staff ID") },
      { name: "grade", label: t("Grade") },
      { name: "currentPosition", label: t("Current Position") },
      { 
        name: "active", 
        label: t("Active"),
        type: "checkbox"
      },
      // {
      //   name: "action",
      //   label: t("Actions"),
      //   onClick: deleteClick,
      //   buttonIcon: <DeleteIcon />,
      //   color: "error",
      //   isHidden: !maintainStaff,
      // },
    ],
    [t, onStaffClick, deleteClick]
  );
  // postData.teamId = team[index].id

  return (
    <>
      …
      <SearchBox
        criteria={searchCriteria}
        onSearch={(query) => {
          // console.log(teamCombo.findIndex(team => team === query.team))
          setFilteredStaff(
            staff.filter(
              (s) =>
                s.staffId.toLowerCase().includes(query.staffId.toLowerCase()) 
                && s.name.toLowerCase().includes(query.name.toLowerCase()) 
                && (query.team === "All" || s.teamId === teams[teamCombo.findIndex(team => team === query.team)].id)
                && (query.grade === "All" || s.grade === query.grade)
                && (query.currentPosition === "All" || s.currentPosition === query.currentPosition)
                && (query.active === "All" || s.active.toString() === query.active)
            )
          );
        }}
      />
      <SearchResults<StaffResult> items={filteredStaff} columns={columns} />

      <Stack
        direction="row"
        justifyContent="flex-end"
        flexWrap="wrap"
        rowGap={2}
      >
        <Button
          variant="contained"
          startIcon={<FileDownloadIcon />}
          onClick={() => handleExport(filteredStaff.map(staff => staff.id))}
        >
          {t("Export")}
        </Button> 
      </Stack>
    </>
  );
};

export default StaffSearch;
