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

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

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

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

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

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

  if (!open) return null;

  const columns = [
    { title: t("jobs.fields.dms.id"), dataIndex: ["id", "value"], 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.name1"),
      dataIndex: ["name1", "fullName"],
      key: "name1",
      sorter: (a, b) => alphaSort(a.name1?.fullName, b.name1?.fullName)
    },
    {
      title: t("jobs.fields.dms.address"),
      key: "address",
      render: (record) =>
        `${record.address?.addressLine && record.address.addressLine[0]}, ${record.address?.city} ${
          record.address?.stateOrProvince
        } ${record.address?.postalCode}`
    }
  ];

  const rowKey = (r) => r.id?.value || r.customerId;

  return (
    <Col span={24}>
      <Table
        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}
        rowKey={rowKey}
        dataSource={customerList}
        rowSelection={{
          onSelect: (r) => {
            const key = r.id?.value || r.customerId;
            setSelectedCustomer(key ? String(key) : null);
          },
          type: "radio",
          selectedRowKeys: selectedCustomer ? [selectedCustomer] : []
        }}
      />
    </Col>
  );
}
