"use client";

import { CompanyResult } from "@/app/api/companys";
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 { useRouter } from "next/navigation";
import { deleteDialog, successDialog } from "../Swal/CustomAlerts";
import { deleteCompany } from "@/app/api/companys/actions";
import DeleteIcon from '@mui/icons-material/Delete';
import { MAINTAIN_COMPANY } from "@/middleware";

interface Props {
  companys: CompanyResult[];
  abilities: String[];
}

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

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

  const router = useRouter()

  const [filteredCompanys, setFilteredCompanys] = useState(companys);

  const maintainCompany = abilities.includes(MAINTAIN_COMPANY)

  const searchCriteria: Criterion<SearchParamNames>[] = useMemo(
    () => [
      { label: t("Company code"), paramName: "companyCode", type: "text" },
      { label: t("Company name"), paramName: "name", type: "text" },
      { label: t("Contact Name"), paramName: "contactName", type: "text" },
      { label: t("Contact Number"), paramName: "phone", type: "text" },
    ],
    [t, companys],
  );

  const onReset = useCallback(() => {
    setFilteredCompanys(companys);
  }, [companys]);

  const onProjectClick = useCallback((company: CompanyResult) => {
    console.log(company);
    router.push(`/settings/company/edit?id=${company.id}`);
  }, []);

  const onDeleteClick = useCallback((company: CompanyResult) => {

    deleteDialog(async() => {
          await deleteCompany(company.id)
  
          successDialog("Delete Success", t)
  
          setFilteredCompanys((prev) => prev.filter((obj) => obj.id !== company.id))
      }, t)
    }, []);

  const columns = useMemo<Column<CompanyResult>[]>(
    () => [
      {
        name: "id",
        label: t("Details"),
        onClick: onProjectClick,
        buttonIcon: <EditNote />,
        isHidden: !maintainCompany,
      },
      { name: "companyCode", label: t("Company Code") },
      { name: "name", label: t("Company Name") },
      { name: "brNo", label: t("Br No.") },
      { name: "contactName", label: t("Contact Name") },
      { name: "phone", label: t("Contact No.") },
      { name: "email", label: t("Contact Email") },
      {
        name: "id",
        label: t("Delete"),
        onClick: onDeleteClick,
        buttonIcon: <DeleteIcon />,
        color: "error",
        isHidden: !maintainCompany,
      },
    ],
    [t, onProjectClick],
  );

  return (
    <>
      <SearchBox
        criteria={searchCriteria}
        onSearch={(query) => {
          setFilteredCompanys(
            companys.filter(
              (p) =>
                p.companyCode.toLowerCase().includes(query.companyCode.toLowerCase()) &&
                p.name.toLowerCase().includes(query.name.toLowerCase()) &&
                p.contactName.toLowerCase().includes(query.contactName.toLowerCase()) &&
                p.phone.toLowerCase().includes(query.phone.toLowerCase()) &&
                {/*(query.client === "All" || p.client === query.client) &&
                (query.category === "All" || p.category === query.category) &&
                (query.team === "All" || p.team === query.team), **/}
            ),
          );
        }}
        onReset={onReset}
      />
      <SearchResults<CompanyResult>
        items={filteredCompanys}
        columns={columns}
      />
    </>
  );
};

export default CompanySearch;
