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 PBSCustomerSelector({ bodyshop, socket }) {
  const { t } = useTranslation();
  const [open, setOpen] = useState(false);
  const [customerList, setCustomerList] = useState([]);
  const [selectedCustomer, setSelectedCustomer] = useState(null);

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

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

  // Restores old behavior: reuse the CDK-named generic number for PBS too,
  // matching the previous single-component implementation.
  const onUseGeneric = () => {
    const generic = bodyshop?.cdk_configuration?.generic_customer_number || null;
    if (!generic) return;
    setOpen(false);
    socket.emit("pbs-selected-customer", generic);
    setSelectedCustomer(null);
  };

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

  if (!open) return null;

  const columns = [
    { title: t("jobs.fields.dms.id"), dataIndex: "Code", key: "ContactId" },
    {
      title: t("jobs.fields.dms.IsARCustomer"),
      dataIndex: "IsARCustomer",
      key: "IsARCustomer",
      render: (text, record) => <Checkbox checked={record.IsARCustomer} disabled />
    },
    {
      title: t("jobs.fields.dms.name1"),
      key: "name1",
      sorter: (a, b) => alphaSort(a.LastName, b.LastName),
      render: (_t, r) => `${r.FirstName || ""} ${r.LastName || ""}`
    },
    {
      title: t("jobs.fields.dms.address"),
      key: "address",
      render: (r) => `${r.Address}, ${r.City} ${r.State} ${r.ZipCode}`
    }
  ];

  const hasGeneric = !!bodyshop?.cdk_configuration?.generic_customer_number;

  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={!hasGeneric}>
              {t("jobs.actions.dms.usegeneric")}
            </Button>
            <Button onClick={onCreateNew}>{t("jobs.actions.dms.createnewcustomer")}</Button>
          </div>
        )}
        pagination={{ placement: "top" }}
        columns={columns}
        mobileColumnKeys={["ContactId", "name1", "address"]}
        rowKey={(r) => r.ContactId}
        dataSource={customerList}
        rowSelection={{
          onSelect: (r) => setSelectedCustomer(r?.ContactId ? String(r.ContactId) : null),
          type: "radio",
          selectedRowKeys: selectedCustomer ? [selectedCustomer] : []
        }}
      />
    </Col>
  );
}
