import { HeartOutlined } from "@ant-design/icons";
import { Select, Space, Tag } from "antd";
import { useEffect, useState } from "react";
import PhoneNumberFormatter from "../../utils/PhoneFormatter";

// To be used as a form element only.

const VendorSearchSelect = ({ value, onChange, options, onSelect, disabled, preferredMake, showPhone, ref }) => {
  const [option, setOption] = useState(value);

  // Sync internal state when value prop changes (e.g., from form.setFieldsValue)
  useEffect(() => {
    if (value !== option) {
      setOption(value);
    }
  }, [value, option]);

  const handleChange = (newValue) => {
    setOption(newValue);
    if (onChange) {
      onChange(newValue);
    }
  };

  const favorites =
    preferredMake && options
      ? options.filter((o) => o.favorite.filter((f) => f.toLowerCase() === preferredMake.toLowerCase()).length > 0)
      : [];

  const formatOption = (o, isFavorite = false) => ({
    key: isFavorite ? `favorite-${o.id}` : o.id,
    value: o.id,
    name: o.name,
    discount: o.discount,
    label: (
      <div
        style={{
          display: "flex",
          alignItems: "center",
          flexWrap: "nowrap",
          width: "100%"
        }}
      >
        <div
          style={{
            flex: 1,
            minWidth: 0,
            overflow: "hidden",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap"
          }}
        >
          {o.name}
        </div>
        <Space style={{ marginLeft: "1rem" }}>
          {isFavorite && <HeartOutlined style={{ color: "red" }} />}
          {!isFavorite &&
            o.tags?.map((tag, idx) => (
              <Tag key={idx} style={{ marginLeft: "0.5rem" }}>
                {tag}
              </Tag>
            ))}
          {o.phone && showPhone && <PhoneNumberFormatter>{o.phone}</PhoneNumberFormatter>}
          {o.discount && o.discount !== 0 ? <Tag color="green">{`${o.discount * 100}%`}</Tag> : null}
        </Space>
      </div>
    )
  });

  const allOptions = [
    ...(favorites?.map((o) => formatOption(o, true)) || []),
    ...(options?.map((o) => formatOption(o, false)) || [])
  ];

  return (
    <Select
      ref={ref}
      showSearch={{
        optionFilterProp: "name"
      }}
      value={option}
      style={{
        width: "100%"
      }}
      labelRender={({ label, value }) => {
        if (!value || !options) return label;
        const discount = options?.find((o) => o.id === value)?.discount;
        return (
          <div
            style={{
              display: "flex",
              alignItems: "center",
              flexWrap: "nowrap",
              width: "100%"
            }}
          >
            <div
              style={{
                flex: 1,
                minWidth: 0,
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap"
              }}
            >
              {label}
            </div>

            {discount && discount !== 0 ? <Tag color="green">{`${discount * 100}%`}</Tag> : null}
          </div>
        );
      }}
      popupMatchSelectWidth={false}
      onChange={handleChange}
      onSelect={onSelect}
      disabled={disabled || false}
      optionLabelProp="name"
      options={allOptions}
    />
  );
};
export default VendorSearchSelect;
