import { motion } from "framer-motion";
import Typography from "../../components/Typography/Typography";
import { useUserProfileStore } from "../../context/zustand-store/userStore";
import { formatStampDateTime, formatTime } from "../../utils/formatTime";

export type TransactionDetailsProps = {
  transaction: any;
  items: any[];
};

const maskShaba = (shaba: string): string => {
  if (!shaba || shaba.length < 8) return shaba;
  const firstTwo = shaba.substring(0, 2);
  const lastSix = shaba.substring(shaba.length - 6);
  const middleLength = shaba.length - 8;
  const masked = firstTwo + "*".repeat(middleLength) + lastSix;
  return masked;
};

const TransactionDetails = ({
  transaction,
  items,
}: TransactionDetailsProps) => {
  const { profile } = useUserProfileStore();

  const processShares = (shares: any[]): any[] => {
    if (!shares || shares.length === 0) return [];

    const processedShares = shares.map((share) => ({ ...share }));

    const mainAccountShares = processedShares.filter(
      (share) => share?.name === "حساب اصلی"
    );

    mainAccountShares.forEach((mainShare) => {
      const matchingShare = processedShares.find(
        (share) =>
          share?.name !== "حساب اصلی" &&
          share?.shaba === mainShare?.shaba &&
          share?.shaba
      );

      if (matchingShare) {
        matchingShare.price =
          (matchingShare.price || 0) + (mainShare.price || 0);
        mainShare._matched = true;
      }
    });

    return processedShares.filter(
      (share) => share?.name !== "حساب اصلی" || !share._matched
    );
  };

  const shareTotals = items.reduce((acc: any, item: any) => {
    if (item?.item_share && item.item_share.length > 0) {
      const processedShares = processShares(item.item_share);
      processedShares.forEach((share: any) => {
        const key = share.shaba || share.name || "unknown";
        if (!acc[key]) {
          acc[key] = {
            name: share.name || "-",
            shaba: share.shaba || "-",
            total: 0,
          };
        }
        acc[key].total += share.price || 0;
      });
    }
    return acc;
  }, {});

  const shareTotalsArray = Object.values(shareTotals);

  if (!items || items.length === 0) {
    return (
      <div className="flex items-center justify-center py-8">
        <Typography
          variant="body2"
          className="text-gray-500 dark:text-gray-300"
        >
          موردی یافت نشد
        </Typography>
      </div>
    );
  }

  return (
    <div className="flex flex-col gap-4">
      {transaction && (
        <div className="bg-gradient-to-r from-slate-50 to-gray-50 dark:from-gray-800 dark:to-gray-700 rounded-lg shadow-sm border border-gray-200 dark:border-gray-600 p-3">
          <div className="flex items-center gap-2 mb-3">
            <div className="w-1 h-5 bg-primary-500 dark:bg-primary-400 rounded-full"></div>
            <Typography
              variant="subtitle1"
              className="text-gray-900 dark:text-white font-bold"
            >
              اطلاعات دامدار
            </Typography>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-2">
            <div className="bg-white dark:bg-gray-800/50 rounded p-2 border border-gray-200 dark:border-gray-600">
              <Typography
                variant="caption"
                className="text-gray-500 dark:text-gray-300 text-xs mb-1"
              >
                نام دامدار
              </Typography>
              <Typography
                variant="caption"
                className="text-gray-900 dark:text-white font-semibold text-sm"
              >
                {transaction?.rancher_fullname || "آزاد"}
              </Typography>
            </div>
            <div className="bg-white dark:bg-gray-800/50 rounded p-2 border border-gray-200 dark:border-gray-600">
              <Typography
                variant="caption"
                className="text-gray-500 dark:text-gray-300 text-xs mb-1"
              >
                تعاونی
              </Typography>
              <Typography
                variant="caption"
                className="text-gray-900 dark:text-white font-semibold text-sm"
              >
                {transaction?.seller_organization?.name || "-"}
              </Typography>
            </div>
            <div className="bg-white dark:bg-gray-800/50 rounded p-2 border border-gray-200 dark:border-gray-600">
              <Typography
                variant="caption"
                className="text-gray-500 dark:text-gray-300 text-xs mb-1"
              >
                شناسه تراکنش
              </Typography>
              <Typography
                variant="caption"
                className="text-gray-900 dark:text-white font-semibold text-sm font-mono"
              >
                {transaction?.transaction_id || "-"}
              </Typography>
            </div>
            <div className="bg-white dark:bg-gray-800/50 rounded p-2 border border-gray-200 dark:border-gray-600">
              <Typography
                variant="caption"
                className="text-gray-500 dark:text-gray-300 text-xs mb-1"
              >
                کد ارجاع
              </Typography>
              <Typography
                variant="caption"
                className="text-gray-900 dark:text-white font-semibold text-sm font-mono"
              >
                {transaction?.ref_num || "-"}
              </Typography>
            </div>
            <div className="bg-white dark:bg-gray-800/50 rounded p-2 border border-gray-200 dark:border-gray-600">
              <Typography
                variant="caption"
                className="text-gray-500 dark:text-gray-300 text-xs mb-1"
              >
                تاریخ
              </Typography>
              <Typography
                variant="caption"
                className="text-gray-900 dark:text-white font-semibold text-sm"
              >
                {formatTime(formatStampDateTime(transaction?.pos_date)) || "-"}
              </Typography>
            </div>

            <div className="bg-white dark:bg-gray-800/50 rounded p-2 border border-gray-200 dark:border-gray-600">
              <Typography
                variant="caption"
                className="text-gray-500 dark:text-gray-300 text-xs mb-1"
              >
                مبلغ کل
              </Typography>
              <Typography
                variant="caption"
                className="text-green-600 dark:text-green-400 font-semibold text-sm"
              >
                {(
                  transaction?.price_paid || transaction?.transaction_price
                )?.toLocaleString() || "-"}{" "}
                ریال
              </Typography>
            </div>
            <div className="bg-white dark:bg-gray-800/50 rounded p-2 border border-gray-200 dark:border-gray-600">
              <Typography
                variant="caption"
                className="text-gray-500 dark:text-gray-300 text-xs mb-1"
              >
                وضعیت پرداخت
              </Typography>
              <Typography
                variant="caption"
                color={`${
                  transaction?.transaction_status === "success"
                    ? "text-green-600 dark:text-green-400"
                    : transaction?.transaction_status === "failed"
                    ? "text-red-600 dark:text-red-400"
                    : "text-orange-600 dark:text-orange-400"
                }`}
                className={`font-semibold text-sm `}
              >
                {transaction?.transaction_status === "waiting"
                  ? "درحال انتظار"
                  : transaction?.transaction_status === "success"
                  ? "موفق"
                  : transaction?.transaction_status === "failed"
                  ? `ناموفق ( ${transaction?.result_text || "-"} ${
                      transaction?.transaction_status_code || ""
                    } )`
                  : "-"}
              </Typography>
            </div>
          </div>
        </div>
      )}
      {shareTotalsArray.length > 0 && (
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-4">
          <Typography
            variant="subtitle1"
            className="text-gray-900 dark:text-white font-bold mb-3"
          >
            خلاصه تسهیم گیرندگان
          </Typography>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2">
            {shareTotalsArray.map((share: any, index: number) => (
              <motion.div
                key={index}
                initial={{ opacity: 0, y: 5 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.2, delay: index * 0.05 }}
                className="bg-gradient-to-r from-primary-50 to-primary-100/50 dark:from-gray-700 dark:to-gray-800 rounded-lg p-3 border border-primary-200 dark:border-gray-600"
              >
                <Typography
                  variant="caption"
                  className="text-gray-900 dark:text-white font-semibold text-sm mb-1"
                >
                  {share.name}
                </Typography>

                <Typography
                  variant="caption"
                  className="text-primary-600 dark:text-primary-400 font-bold text-base"
                >
                  {share.total.toLocaleString()} ریال
                </Typography>
              </motion.div>
            ))}
          </div>
        </div>
      )}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
        {items.map((item, index) => (
          <motion.div
            key={item?.id || index}
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.2, delay: index * 0.02 }}
            className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden"
          >
            <div className="px-3 py-2 bg-gradient-to-r from-primary-50 to-primary-100/50 dark:from-gray-700 dark:to-gray-800 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
              <Typography
                variant="subtitle2"
                className="text-gray-900 dark:text-white font-semibold"
              >
                {item?.name || "-"}
              </Typography>
              <Typography
                variant="caption"
                className="text-primary-600 dark:text-primary-400 font-bold bg-primary-100 dark:bg-primary-900/30 px-2 py-0.5 rounded"
              >
                {index + 1}
              </Typography>
            </div>

            <div className="p-2">
              <div className="grid grid-cols-2 gap-2 mb-3">
                <div className="bg-gray-50 dark:bg-gray-700/50 rounded p-2">
                  <Typography
                    variant="caption"
                    className="text-gray-500 dark:text-gray-300 text-xs mb-0.5"
                  >
                    مبلغ واحد
                  </Typography>
                  <Typography
                    variant="caption"
                    className="text-gray-900 dark:text-white font-semibold text-xs"
                  >
                    {item?.unit_price?.toLocaleString() || "-"} ریال
                  </Typography>
                </div>

                <div className="bg-gray-50 dark:bg-gray-700/50 rounded p-2">
                  <Typography
                    variant="caption"
                    className="text-gray-500 dark:text-gray-300 text-xs mb-0.5"
                  >
                    وزن
                  </Typography>
                  <Typography
                    variant="caption"
                    className="text-gray-900 dark:text-white font-semibold text-xs"
                  >
                    {item?.weight?.toLocaleString()}{" "}
                    {item?.unit === "kg" ? "کیلوگرم" : item?.unit}
                  </Typography>
                </div>

                <div className="bg-gray-50 dark:bg-gray-700/50 rounded p-2">
                  <Typography
                    variant="caption"
                    className="text-gray-500 dark:text-gray-300 text-xs mb-0.5"
                  >
                    صورت حساب
                  </Typography>
                  <Typography
                    variant="caption"
                    className="text-gray-900 dark:text-white font-semibold text-xs"
                  >
                    {item?.total_price?.toLocaleString() || "-"} ریال
                  </Typography>
                </div>

                <div className="bg-gray-50 dark:bg-gray-700/50 rounded p-2">
                  <Typography
                    variant="caption"
                    className="text-gray-500 dark:text-gray-300 text-xs mb-0.5"
                  >
                    مبلغ پرداخت شده
                  </Typography>
                  <Typography
                    variant="caption"
                    className="text-green-600 dark:text-green-400 font-semibold text-xs"
                  >
                    {item?.paid_price?.toLocaleString() || "-"} ریال
                  </Typography>
                </div>
              </div>

              <div className="mb-2 grid grid-cols-1 md:grid-cols-2 gap-2">
                <div className="bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-900/20 dark:to-indigo-900/20 rounded-lg p-2 border border-blue-200 dark:border-blue-800/50">
                  <div className="flex items-center gap-1.5 mb-1.5">
                    <div className="w-1 h-4 bg-blue-500 dark:bg-blue-400 rounded-full"></div>
                    <Typography
                      variant="caption"
                      className="text-gray-700 dark:text-gray-100 font-bold text-[10px] uppercase tracking-wide"
                    >
                      نوع فروش
                    </Typography>
                  </div>
                  <div className="flex items-center gap-1.5">
                    <div
                      className={`w-1.5 h-1.5 rounded-full ${
                        item?.item_type === "COUNT"
                          ? "bg-orange-500"
                          : "bg-purple-500"
                      }`}
                    ></div>
                    <Typography
                      variant="caption"
                      className="text-gray-900 dark:text-white font-semibold text-xs"
                    >
                      {item?.item_type === "COUNT"
                        ? "بر اساس تعداد راس دام"
                        : "بر اساس وزن"}
                    </Typography>
                  </div>
                </div>

                {item?.livestock_statistic &&
                  item.livestock_statistic.length > 0 && (
                    <div className="bg-gradient-to-r from-emerald-50 to-teal-50 dark:from-emerald-900/20 dark:to-teal-900/20 rounded-lg p-2 border border-emerald-200 dark:border-emerald-800/50">
                      <div className="flex items-center gap-1.5 mb-1.5">
                        <div className="w-1 h-4 bg-emerald-500 dark:bg-emerald-400 rounded-full"></div>
                        <Typography
                          variant="caption"
                          className="text-gray-700 dark:text-gray-100 font-bold text-[10px] uppercase tracking-wide"
                        >
                          جزئیات فروش
                        </Typography>
                      </div>
                      <div className="space-y-1 max-h-40 overflow-y-auto">
                        {item.livestock_statistic.map(
                          (livestockStatic: any, statIndex: number) => (
                            <motion.div
                              key={statIndex}
                              initial={{ opacity: 0, x: -5 }}
                              animate={{ opacity: 1, x: 0 }}
                              transition={{
                                duration: 0.15,
                                delay: statIndex * 0.05,
                              }}
                              className="bg-white dark:bg-gray-800/50 rounded p-1.5 border border-emerald-200/50 dark:border-emerald-700/30"
                            >
                              <div className="flex items-center justify-between gap-1.5">
                                <div className="flex items-center gap-1.5 min-w-0 flex-1">
                                  <div className="w-5 h-5 rounded-full bg-emerald-100 dark:bg-emerald-900/30 flex items-center justify-center flex-shrink-0">
                                    <Typography
                                      variant="caption"
                                      className="text-emerald-600 dark:text-emerald-400 font-bold text-[10px]"
                                    >
                                      {statIndex + 1}
                                    </Typography>
                                  </div>
                                  <Typography
                                    variant="caption"
                                    className="text-gray-900 dark:text-white font-semibold text-xs truncate"
                                  >
                                    {livestockStatic?.name_fa || "-"}
                                  </Typography>
                                </div>
                                <div className="bg-emerald-100 dark:bg-emerald-900/30 px-1.5 py-0.5 rounded-full flex-shrink-0">
                                  <Typography
                                    variant="caption"
                                    className="text-emerald-700 dark:text-emerald-300 font-bold text-[10px]"
                                  >
                                    {livestockStatic?.count?.toLocaleString() ||
                                      "0"}{" "}
                                    راس
                                  </Typography>
                                </div>
                              </div>
                            </motion.div>
                          )
                        )}
                      </div>
                    </div>
                  )}
              </div>

              {item?.item_share && item.item_share.length > 0 && (
                <div className="mt-2">
                  <Typography
                    variant="caption"
                    className="text-gray-700 dark:text-gray-100 mb-1.5 font-semibold text-xs"
                  >
                    تسهیم
                  </Typography>
                  <div className="space-y-1">
                    {processShares(item.item_share).map(
                      (share: any, shareIndex: number) => (
                        <motion.div
                          key={shareIndex}
                          initial={{ opacity: 0, x: -5 }}
                          animate={{ opacity: 1, x: 0 }}
                          transition={{
                            duration: 0.15,
                            delay: shareIndex * 0.02,
                          }}
                          className="bg-primary-50/50 dark:bg-gray-700/30 rounded p-1.5 border border-primary-200/50 dark:border-gray-600"
                        >
                          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1">
                            <div className="flex-1 min-w-0">
                              <Typography
                                variant="caption"
                                className="text-gray-900 dark:text-white font-medium text-xs truncate"
                              >
                                {share?.name || "-"}
                              </Typography>
                              {profile?.role?.type?.key === "ADM" ? (
                                <Typography
                                  variant="caption"
                                  className="text-gray-500 dark:text-gray-300 font-mono text-[12px] truncate"
                                >
                                  شبا: {share.shaba}
                                </Typography>
                              ) : (
                                <Typography
                                  variant="caption"
                                  className="text-gray-500 dark:text-gray-300 font-mono text-[12px] truncate"
                                >
                                  شبا: {maskShaba(share.shaba)}
                                </Typography>
                              )}
                            </div>
                            <div className="flex items-center gap-1">
                              <Typography
                                variant="caption"
                                className="text-primary-600 dark:text-primary-400 font-semibold text-xs whitespace-nowrap"
                              >
                                {share?.price?.toLocaleString() || "-"} ریال
                              </Typography>
                            </div>
                          </div>
                        </motion.div>
                      )
                    )}
                  </div>
                </div>
              )}
            </div>
          </motion.div>
        ))}
      </div>
    </div>
  );
};

export default TransactionDetails;
