import { PlusOutlined, SearchOutlined } from "@ant-design/icons";
import { Button, Input, Popover } from "antd";
import ResponsiveTable from "../responsive-table/responsive-table.component";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import PredefinedVehicles from "./predefined-vehicles.js";

export default function JobsCreateVehicleInfoPredefined({ disabled, form }) {
  const [open, setOpen] = useState(false);
  const [search, setSearch] = useState("");
  const { t } = useTranslation();
  const handleOpenChange = (newOpen) => {
    setOpen(newOpen);
    setSearch("");
  };
  const filteredPredefinedVehicles =
    search === ""
      ? PredefinedVehicles
      : PredefinedVehicles.filter(
          (v) =>
            v.make.toLowerCase().includes(search.toLowerCase()) || v.model.toLowerCase().includes(search.toLowerCase())
        );

  const popContent = () => (
    <div>
      <ResponsiveTable
        size="small"
        title={() => <Input.Search onSearch={(value) => setSearch(value)} enterButton />}
        dataSource={filteredPredefinedVehicles}
        columns={[
          {
            dataIndex: "make",
            key: "make",
            title: t("vehicles.fields.v_make_desc")
          },
          {
            dataIndex: "model",
            key: "model",
            title: t("vehicles.fields.v_model_desc")
          },
          {
            dataIndex: "select",
            key: "select",
            title: t("general.labels.actions"),
            render: (value, record) => (
              <Button
                disabled={disabled}
                onClick={() => {
                  form.setFieldsValue({
                    vehicle: {
                      data: {
                        v_make_desc: record.make,
                        v_model_desc: record.model
                      }
                    }
                  });
                  setOpen(false);
                  setSearch("");
                }}
                icon={<PlusOutlined />}
              />
            )
          }
        ]}
        mobileColumnKeys={["make", "model", "select"]}
      />
    </div>
  );
  return (
    <Popover
      content={popContent}
      trigger="click"
      open={open}
      placement="left"
      onOpenChange={handleOpenChange}
      destroyOnHidden
    >
      <SearchOutlined style={{ cursor: "pointer" }} />
    </Popover>
  );
}
