import React, { useMemo } from "react";
import { List, Dropdown, Button, Menu, Tag } from "antd";
import { DownOutlined } from "@ant-design/icons";
import Link from "next/link";

// ✅ Component 1: Normal / Currency / Action
export const ListData = ({ data = [], type = "normal", mobileView }) => {
  const formatCurrency = (value) => {
    if (typeof value !== "number") return value;
    return `AED ${value.toLocaleString("en-IN", {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    })}`;
  };

  return (
    <List
      size="large"
      itemLayout="horizontal"
      dataSource={data}
      renderItem={(item, index) => (
        <List.Item key={index} className="px-0">
          <div
            className={
              mobileView
                ? "sm:flex grid gap-3 justify-between items-center w-full"
                : "flex justify-between items-center w-full"
            }
          >
            <div className="text-neutral-600 text-xs font-normal leading-tight">
              {item?.title || ""}
            </div>

            <div className="flex flex-col sm:flex-row gap-1 sm:gap-2 sm:items-end text-xs font-semibold leading-tight sm:text-right">
              {React.isValidElement(item?.value) ? (
                item.value
              ) : type === "currency" ? (
                <span>{formatCurrency(item?.value)}</span>
              ) : type === "html" ? (
                <span dangerouslySetInnerHTML={{ __html: item?.value }} />
              ) : (
                <span>{item?.value}</span>
              )}
              {item?.field && <span>{item.field}</span>}
            </div>
          </div>
        </List.Item>
      )}
    />
  );
};

// Props: data = array of items with status and title
export const ListDataWithBadge = ({ data = [], type }) => {
  const getBadgeConfig = (status = "") => {
    switch (status.toLowerCase()) {
      case "paid":
      case "approved":
      case "active":
        return { color: "green", content: "Active" };
      case "sent":
        return { color: "orange", content: "Sent" };
      case "accepted":
        return { color: "blue", content: "Accepted" };
      case "draft":
        return { color: "default", content: "Draft" };
      case "rejected":
        return { color: "red", content: "Rejected" };
      default:
        return { color: "default", content: status || "?" };
    }
  };

  const getTitle = (item) => {
    if (type === "customer") {
      if (item.customer_type === "Company" && item.company_name) {
        return item.company_name;
      } else if (item.customer_type === "Individual" && item.display_name) {
        return item.display_name;
      }
      return item.customer_name || "Unnamed Customer";
    }

    const numberKey = Object.keys(item || {}).find((key) =>
      key.endsWith("_number")
    );
    return numberKey ? item[numberKey] : "Untitled";
  };

  const getItemId = (item) => {
    const key = Object.keys(item).find((k) => k.endsWith("_id"));
    return item[key];
  };

  return (
    <List
      size="large"
      itemLayout="horizontal"
      dataSource={data}
      renderItem={(item, index) => {
        const badge = getBadgeConfig(item?.status || item?.customer_status);
        const title = getTitle(item);
        const id = getItemId(item);

        return (
          <List.Item
            key={index}
            className="px-0"
            style={{ padding: "15px 20px" }}
          >
            <div className="text-neutral-700">
              <Link
                href={`/${type}/view/${id}`}
                className="flex justify-between items-center !text-[12px]  !text-black w-full !hover:text-blue-600 rounded transition"
              >
                {title}
              </Link>
            </div>
            <Tag color={badge.color}>{badge.content}</Tag>
          </List.Item>
        );
      }}
    />
  );
};


// ✅ Component 3: Dropdown-based Action (supports 'delete' type)
export const ListDataWithDropdown = ({
  data = [],
  buttonLabel = "Actions",
  getMenuItems = () => [],
  onMenuClick = () => {},
  mobileView,
  type = "default", // added type prop
}) => {
  return (
    <List
      size="large"
      itemLayout="horizontal"
      dataSource={data}
      renderItem={(item, index) => {
        const handleClick = () => onMenuClick("delete", item, index);

        const menu = (
          <Menu
            items={getMenuItems(item, index)}
            onClick={({ key }) => onMenuClick(key, item, index)}
          />
        );

        return (
          <List.Item key={index} className="px-0">
            <div
              className={
                mobileView
                  ? "sm:flex grid gap-3 justify-between items-center w-full"
                  : "flex justify-between items-center w-full"
              }
            >
              <div className="text-neutral-600 text-xs font-normal leading-tight">
                {item?.title || item?.item || ""}
              </div>

              {type === "delete" ? (
                <Button size="small" danger onClick={handleClick}>
                  Delete
                </Button>
              ) : (
                <Dropdown overlay={menu} trigger={["click"]}>
                  <Button size="small">
                    {buttonLabel} <DownOutlined />
                  </Button>
                </Dropdown>
              )}
            </div>
          </List.Item>
        );
      }}
    />
  );
};
