import { useState, useMemo } from "react";
import { Grid } from "../../components/Grid/Grid";
import Typography from "../../components/Typography/Typography";
import { BrokerSharingSummary } from "../../types/transactions";
import { convertNumberToPersian } from "../../utils/convertNumberToPersian";
import { MagnifyingGlassIcon } from "@heroicons/react/24/outline";
import AutoComplete from "../../components/AutoComplete/AutoComplete";
import Textfield from "../../components/Textfeild/Textfeild";

type TransactionSharingDetailsProps = {
  data?: BrokerSharingSummary[];
};

type SortOption = "most-to-least" | "least-to-most" | "by-count" | "";

const sortOptions = [
  { key: "most-to-least", value: "بیشترین سهم" },
  { key: "least-to-most", value: "کمترین سهم" },
  { key: "by-count", value: "تعداد تراکنش" },
];

const TransactionSharingDetails = ({
  data,
}: TransactionSharingDetailsProps) => {
  const [searchTerm, setSearchTerm] = useState<string>("");
  const [sortOption, setSortOption] = useState<SortOption>("");
  const [selectedSortKeys, setSelectedSortKeys] = useState<(number | string)[]>(
    []
  );

  const filteredData = useMemo(() => {
    let result =
      data?.filter(
        (item: BrokerSharingSummary) => item?.name !== "حساب اصلی"
      ) || [];

    if (searchTerm.trim()) {
      result = result.filter((item: BrokerSharingSummary) =>
        item?.name?.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    if (sortOption === "most-to-least") {
      result = [...result].sort(
        (a, b) => (b?.total_price || 0) - (a?.total_price || 0)
      );
    } else if (sortOption === "least-to-most") {
      result = [...result].sort(
        (a, b) => (a?.total_price || 0) - (b?.total_price || 0)
      );
    } else if (sortOption === "by-count") {
      result = [...result].sort((a, b) => (b?.count || 0) - (a?.count || 0));
    }

    return result;
  }, [data, searchTerm, sortOption]);

  if (
    !filteredData ||
    !Array.isArray(filteredData) ||
    filteredData.length === 0
  ) {
    return (
      <Grid container column className="gap-4">
        <div className="flex flex-col sm:flex-row gap-3">
          <div className="flex-1">
            <Textfield
              placeholder="جستجو..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              fullWidth
              inputSize="small"
              end={<MagnifyingGlassIcon className="h-5 w-5 text-gray-400" />}
            />
          </div>
          <div className="min-w-[200px]">
            <AutoComplete
              data={sortOptions}
              selectedKeys={selectedSortKeys}
              onChange={(keys) => {
                setSelectedSortKeys(keys);
                setSortOption((keys[0] as SortOption) || "");
              }}
              title="مرتب‌ سازی"
              size="small"
              inPage={true}
              selectField={true}
            />
          </div>
        </div>

        <div className="flex items-center justify-center py-8">
          <Typography
            variant="body2"
            className="text-gray-500 dark:text-gray-400"
          >
            موردی یافت نشد
          </Typography>
        </div>
      </Grid>
    );
  }

  return (
    <Grid container column className="gap-4">
      <div className="flex flex-col sm:flex-row gap-3">
        <div className="flex-1">
          <Textfield
            placeholder="جستجو..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            fullWidth
            inputSize="small"
            end={<MagnifyingGlassIcon className="h-5 w-5 text-gray-400" />}
          />
        </div>
        <div className="min-w-[200px]">
          <AutoComplete
            data={sortOptions}
            selectedKeys={selectedSortKeys}
            onChange={(keys) => {
              setSelectedSortKeys(keys);
              setSortOption((keys[0] as SortOption) || "");
            }}
            title="مرتب‌سازی"
            size="small"
            inPage={true}
            selectField={true}
          />
        </div>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
        {filteredData.map((item: BrokerSharingSummary, index: number) => (
          <div
            key={index}
            className="bg-white dark:bg-dark-700 rounded-2xl border border-gray-200 dark:border-dark-600 shadow-sm p-4 hover:shadow-md transition-shadow duration-200 flex flex-col h-full"
          >
            <div className="flex flex-col flex-1 space-y-3">
              <div className="flex items-center gap-2 pb-2 border-b border-gray-100 dark:border-dark-600 min-w-0 h-14">
                <span className="flex-shrink-0 flex items-center justify-center w-6 h-6 rounded bg-primary-100 dark:bg-primary-900 text-primary-700 dark:text-primary-300 text-xs font-semibold mt-0.5">
                  {index + 1}
                </span>
                <Typography
                  className="text-gray-900 text-xs dark:text-white font-semibold flex-1 min-w-0 line-clamp-2"
                  title={item?.name || "-"}
                >
                  {item?.name || "-"}
                </Typography>
              </div>

              <div className="flex-1">
                <Typography
                  variant="caption"
                  color="text-gray-500 dark:text-gray-400"
                  className="text-xs mb-1"
                >
                  سهم:
                </Typography>
                <Typography
                  variant="h6"
                  color="text-primary-600 dark:text-primary-300"
                  className="font-bold"
                >
                  {item?.total_price?.toLocaleString() || "0"} ریال
                </Typography>
                <Typography
                  variant="caption"
                  color="text-gray-500 dark:text-gray-400"
                  className="text-xs mt-1"
                >
                  {convertNumberToPersian(item?.total_price || 0)} ریال
                </Typography>
              </div>

              <div className="flex items-center justify-between pt-2 border-t border-gray-100 dark:border-dark-600 mt-auto">
                <Typography
                  variant="body2"
                  className="text-gray-500 dark:text-gray-400 text-xs"
                >
                  تعداد تراکنش:
                </Typography>
                <Typography
                  variant="body2"
                  className="text-gray-900 dark:text-white font-semibold"
                >
                  {item?.count?.toLocaleString() || "0"}
                </Typography>
              </div>
            </div>
          </div>
        ))}
      </div>
    </Grid>
  );
};

export default TransactionSharingDetails;
