import { Card, Form, Select } from "antd";
import PropTypes from "prop-types";
import { useTranslation } from "react-i18next";

const FilterSettings = ({
  selectedMdInsCos,
  setSelectedMdInsCos,
  selectedEstimators,
  setSelectedEstimators,
  setHasChanges,
  bodyshop,
  data
}) => {
  const { t } = useTranslation();

  const extractNames = (source, firstNameKey, lastNameKey) =>
    source.map((item) => ({
      firstName: item[firstNameKey],
      lastName: item[lastNameKey]
    }));

  const bodyshopNames = extractNames(bodyshop.md_estimators, "est_ct_fn", "est_ct_ln");
  const dataNames = extractNames(data, "est_ct_fn", "est_ct_ln");

  const combinedNames = [...bodyshopNames, ...dataNames];

  const uniqueNames = Array.from(
    new Map(combinedNames.map((item) => [`${item.firstName} ${item.lastName}`, item])).values()
  );

  return (
    <Card title={t("production.settings.filters_title")}>
      <Form.Item label={t("production.settings.filters.md_ins_cos")}>
        <Select
          mode="multiple"
          placeholder={t("production.settings.filters.md_ins_cos")}
          value={selectedMdInsCos}
          onChange={(value) => {
            setSelectedMdInsCos(value);
            setHasChanges(true);
          }}
          options={bodyshop.md_ins_cos.map((item) => ({
            value: item.name,
            label: item.name
          }))}
        />
      </Form.Item>
      <Form.Item label={t("production.settings.filters.md_estimators")}>
        <Select
          mode="multiple"
          placeholder={t("production.settings.filters.md_estimators")}
          value={selectedEstimators}
          onChange={(value) => {
            setSelectedEstimators(value);
            setHasChanges(true);
          }}
          options={uniqueNames.map((item) => {
            const name = `${item.firstName} ${item.lastName}`.trim();
            return {
              value: name,
              label: name
            };
          })}
        />
      </Form.Item>
    </Card>
  );
};

FilterSettings.propTypes = {
  selectedMdInsCos: PropTypes.array.isRequired,
  setSelectedMdInsCos: PropTypes.func.isRequired,
  setHasChanges: PropTypes.func.isRequired,
  selectedEstimators: PropTypes.array.isRequired,
  setSelectedEstimators: PropTypes.func,
  bodyshop: PropTypes.object.isRequired,
  data: PropTypes.arrayOf(PropTypes.object).isRequired
};

export default FilterSettings;
