import { Card, CardBody, CardHeader } from "@progress/kendo-react-layout";
import { useState } from "react";
export type CardViewProps = {
  record: any;
  headerField?: string;
  columns?: any[];
  handleClick: (props: any, e: any) => void;
};

const CardGridWidgetView = ({
  record,
  headerField,
  columns,
  handleClick,
}: CardViewProps) => {
  const [isSelecting, setIsSelecting] = useState(false);

  const handleMouseDown = () => {
    setIsSelecting(false);
  };

  const handleMouseUp = () => {
    const selection = window.getSelection();
    if (selection && selection.toString().length > 0) {
      setIsSelecting(true);
    }
  };

  const onClick = (e: any) => {
    if (!isSelecting) {
      handleClick(
        {
          ...(columns?.find((column) => headerField === column.field) || {}),
          dataItem: record,
        },
        e
      );
    }
  };

  return (
    <Card className="prc-infinite-card">
      <CardHeader>
        <h3
          className="prc-infinite-card__title"
          onMouseDown={handleMouseDown}
          onMouseUp={handleMouseUp}
          onClick={onClick}
        >
          {record[headerField ?? ""]}
        </h3>
      </CardHeader>
      <CardBody className="prc-infinite-body">
        {columns?.map((column) => {
          if (headerField === column.field) return <></>;
          return (
            <div className="prc-infinite-card__bodyrow" key={column.id}>
              <b className="prc-infinite-card__key">{column.title}:</b>
              <div
                className="prc-infinite-card__value"
                onClick={(e) => handleClick({ ...column, dataItem: record }, e)}
                title={record[column.field]?.replace(/<[^>]*>/g, "")}
                dangerouslySetInnerHTML={{
                  __html: record[column.field],
                }}
              ></div>
            </div>
          );
        })}
      </CardBody>
    </Card>
  );
};
export default CardGridWidgetView;
