import { Button, Checkbox, Col } from "antd";
import ResponsiveTable from "../responsive-table/responsive-table.component";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { alphaSort } from "../../utils/sorters";

export default function FortellisCustomerSelector({ bodyshop, jobid, socket }) {
  const { t } = useTranslation();
  const [open, setOpen] = useState(false);
  const [customerList, setCustomerList] = useState([]);
  const [selectedCustomer, setSelectedCustomer] = useState(null);

  useEffect(() => {
    if (!socket) return;
    const handleFortellisSelectCustomer = (list) => {
      setOpen(true);
      setCustomerList(Array.isArray(list) ? list : []);
      setSelectedCustomer(null);
    };
    socket.on("fortellis-select-customer", handleFortellisSelectCustomer);
    return () => {
      socket.off("fortellis-select-customer", handleFortellisSelectCustomer);
    };
  }, [socket]);

  const onUseSelected = () => {
    if (!selectedCustomer) return;
    setOpen(false);
    socket.emit("fortellis-selected-customer", { selectedCustomerId: selectedCustomer, jobid });
    setSelectedCustomer(null);
  };

  const onUseGeneric = () => {
    const generic = bodyshop.cdk_configuration?.generic_customer_number || null;
    setOpen(false);
    socket.emit("fortellis-selected-customer", { selectedCustomerId: generic, jobid });
    setSelectedCustomer(null);
  };

  const onCreateNew = () => {
    setOpen(false);
    socket.emit("fortellis-selected-customer", { selectedCustomerId: null, jobid });
    setSelectedCustomer(null);
  };

  if (!open) return null;

  const columns = [
    { title: t("jobs.fields.dms.id"), dataIndex: "customerId", key: "id" },
    {
      title: t("jobs.fields.dms.vinowner"),
      dataIndex: "vinOwner",
      key: "vinOwner",
      render: (_t, r) => <Checkbox disabled checked={r.vinOwner} />
    },
    {
      title: t("jobs.fields.dms.first_name"),
      dataIndex: ["customerName", "firstName"],
      key: "firstName",
      sorter: (a, b) => alphaSort(a.customerName?.firstName, b.customerName?.firstName)
    },
    {
      title: t("jobs.fields.dms.last_name"),
      dataIndex: ["customerName", "lastName"],
      key: "lastName",
      sorter: (a, b) => alphaSort(a.customerName?.lastName, b.customerName?.lastName)
    },
    {
      title: t("jobs.fields.dms.address"),
      key: "address",
      render: (record) =>
        `${record.postalAddress?.addressLine1 || ""}${
          record.postalAddress?.addressLine2 ? `, ${record.postalAddress.addressLine2}` : ""
        }, ${record.postalAddress?.city || ""} ${record.postalAddress?.state || ""} ${
          record.postalAddress?.postalCode || ""
        } ${record.postalAddress?.country || ""}`
    }
  ];

  return (
    <Col span={24}>
      <ResponsiveTable
        title={() => (
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
            <Button onClick={onUseSelected} disabled={!selectedCustomer}>
              {t("jobs.actions.dms.useselected")}
            </Button>
            <Button onClick={onUseGeneric} disabled={!bodyshop.cdk_configuration?.generic_customer_number}>
              {t("jobs.actions.dms.usegeneric")}
            </Button>
            <Button onClick={onCreateNew}>{t("jobs.actions.dms.createnewcustomer")}</Button>
          </div>
        )}
        pagination={{ placement: "top" }}
        columns={columns}
        mobileColumnKeys={["id", "vinOwner", "firstName", "address"]}
        rowKey={(r) => r.customerId}
        dataSource={customerList}
        rowSelection={{
          onSelect: (r) => setSelectedCustomer(r?.customerId ? String(r.customerId) : null),
          type: "radio",
          selectedRowKeys: selectedCustomer ? [selectedCustomer] : []
        }}
      />
    </Col>
  );
}
