import React, { useEffect, useState } from "react";
import styles from "./Transactions.module.css";
import { useParams } from "react-router-dom";
import { ColorRing } from "react-loader-spinner";
import {
  getMyTransactions,
  confirmTransaction,
  declineTransaction,
  getTransactionsFromCafe,
} from "../helpers/transactionHelpers";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";
import { ThreeDots } from "react-loader-spinner";

import ButtonWithReplica from "../components/ButtonWithReplica";

dayjs.extend(utc);
dayjs.extend(timezone);

export default function Transactions({ shop, shopId, propsShopId, sendParam, deviceType, paymentUrl, setModal, newTransaction }) {
  const { shopIdentifier, tableId } = useParams();
  if (sendParam) sendParam({ shopIdentifier, tableId });

  const [transactions, setTransactions] = useState([]);
  const [isPaymentLoading, setIsPaymentLoading] = useState(false);
  const [isPaymentOpen, setIsPaymentOpen] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [matchedItems, setMatchedItems] = useState([]);

  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setMatchedItems(searchAndAggregateItems(transactions, searchTerm));
  }, [searchTerm, transactions]);

  useEffect(() => {
    const fetchTransactions = async () => {
      try {

        //   response = await getMyTransactions(shopId || propsShopId, 5);
        // setMyTransactions(response);
        setLoading(true);
        let response = await getTransactionsFromCafe(shopId || propsShopId, -1, false);

        setLoading(false);
        if (response) setTransactions(response);
      } catch (error) {
        console.error("Error fetching transactions:", error);
      }
    };
    console.log(deviceType)
    fetchTransactions();
  }, [deviceType, newTransaction]);

  const calculateTotalPrice = (detailedTransactions) => {
    return detailedTransactions.reduce((total, dt) => {
      return total + dt.qty * (dt.promoPrice ? dt.promoPrice : dt.price);
    }, 0);
  };
const calculateAllTransactionsTotal = (transactions) => {
  return transactions
    .filter(transaction => transaction.confirmed > 1) // Filter transactions where confirmed > 1
    .reduce((grandTotal, transaction) => {
      return grandTotal + calculateTotalPrice(transaction.DetailedTransactions);
    }, 0);
};
const searchAndAggregateItems = (transactions, searchTerm) => {
  if (!searchTerm.trim()) return [];

  const normalizedTerm = searchTerm.trim().toLowerCase();
  // Map with key = `${itemId}-${confirmedGroup}` to keep confirmed groups separate
  const aggregatedItems = new Map();

  transactions.forEach(transaction => {
    // Determine confirmed group as a string key
    const confirmedGroup = transaction.confirmed >= 0  && transaction.confirmed > 1 ? 'confirmed_gt_1' : 'confirmed_le_1';

    transaction.DetailedTransactions.forEach(detail => {
      const itemName = detail.Item.name;
      const itemNameLower = itemName.toLowerCase();

      if (itemNameLower.includes(normalizedTerm)) {
        // Combine itemId and confirmedGroup to keep them separated
        const key = `${detail.itemId}-${confirmedGroup}`;

        if (!aggregatedItems.has(key)) {
          aggregatedItems.set(key, {
            itemId: detail.itemId,
            name: itemName,
            totalQty: 0,
            totalPrice: 0,
            confirmedGroup, // Keep track of which group this belongs to
          });
        }

        const current = aggregatedItems.get(key);
        current.totalQty += detail.qty;
        current.totalPrice += detail.qty * (detail.promoPrice || detail.price);
      }
    });
  });
console.log(aggregatedItems.values())
  return Array.from(aggregatedItems.values());
};



  const handleConfirm = async (transactionId) => {
    setIsPaymentLoading(true);
    try {
      const result = await confirmTransaction(transactionId);
      if (result) {
        setTransactions(prev =>
          prev.map(t =>
            t.transactionId === transactionId ? result : t
          )
        );
      }
    } catch (error) {
      console.error("Error processing payment:", error);
    } finally {
      setIsPaymentLoading(false);
    }
  };

  const handleDecline = async (transactionId) => {
    setIsPaymentLoading(true);
    try {
      const result = await declineTransaction(transactionId);
      if (result) {
        setTransactions(prev =>
          prev.map(t =>
            t.transactionId === transactionId ? result : t
          )
        );
      }
    } catch (error) {
      console.error("Error processing payment:", error);
    } finally {
      setIsPaymentLoading(false);
    }
  };

  if (loading)
    return (
      <div className="Loader">
        <div className="LoaderChild">
          <ThreeDots />
          <h1></h1>
        </div>
      </div>
    );
  return (
    <div className={styles.Transactions}>
      <h2 className={styles["Transactions-title"]}>
        Transaksi selesai Rp {calculateAllTransactionsTotal(transactions)}
      </h2>

      <input
        type="text"
        placeholder="Cari nama item..."
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
        style={{ border: '0px', height: '42px', borderRadius: '15px', margin: '7px auto 10px', width: '88%', paddingLeft: '8px' }}
      />



      {/* Existing Transactions List (keep all your JSX below unchanged) */}
      <div className={styles.TransactionListContainer} style={{ padding: '0 8px' }}>

        {matchedItems.length > 0 && matchedItems.map(item => (
          <div
 key={`${item.itemId}-${item.confirmedGroup}`}
             className={styles.RoundedRectangle}
            style={{ overflow: "hidden" }}
          >
            <ul>
              <li>
                <strong>{item.name}</strong> x {item.totalQty}
              </li>
            </ul>
            <div className={styles.TotalContainer}>
              <span>Total:</span>
              <span>Rp {item.totalPrice}</span>
            </div>
          </div>
        ))}
        {transactions &&
          transactions.map((transaction) => (
            <div
              key={transaction.transactionId}
              className={styles.RoundedRectangle}
              style={{ overflow: 'hidden' }}
            >

              <div className={styles['receipt-header']}>
                {transaction.confirmed === 1 ? (
                  <ColorRing className={styles['receipt-logo']} />
                ) : transaction.confirmed === -1 && !transaction.is_paid || transaction.confirmed === -2 && !transaction.is_paid ? (
                  <div style={{ display: 'flex', justifyContent: 'center', margin: '16px 0px' }}>
                    <svg
                      style={{ width: '60px', transform: 'Rotate(45deg)' }}
                      clipRule="evenodd"
                      fillRule="evenodd"
                      strokeLinejoin="round"
                      strokeMiterlimit="2"
                      viewBox="0 0 24 24"
                      xmlns="http://www.w3.org/2000/svg"
                    >
                      <path
                        d="m12.002 2c5.518 0 9.998 4.48 9.998 9.998 0 5.517-4.48 9.997-9.998 9.997-5.517 0-9.997-4.48-9.997-9.997 0-5.518 4.48-9.998 9.997-9.998zm0 1.5c-4.69 0-8.497 3.808-8.497 8.498s3.807 8.497 8.497 8.497 8.498-3.807 8.498-8.497-3.808-8.498-8.498-8.498zm-.747 7.75h-3.5c-.414 0-.75.336-.75.75s.336.75.75.75h3.5v3.5c0 .414.336.75.75.75s.75-.336.75-.75v-3.5h3.5c.414 0 .75-.336.75-.75s-.336-.75-.75-.75h-3.5v-3.5c0-.414-.336-.75-.75-.75s-.75.336-.75.75z"
                        fillRule="nonzero"
                      />
                    </svg>
                  </div>
                ) : transaction.confirmed === 2 && !transaction.is_paid ? (
                  <ColorRing className={styles['receipt-logo']} />
                ) : transaction.confirmed === 3 || transaction.is_paid ? (
                  <div>
                    <svg
                      height="60px"
                      width="60px"
                      version="1.1"
                      id="Layer_1"
                      xmlns="http://www.w3.org/2000/svg"
                      xmlnsXlink="http://www.w3.org/1999/xlink"
                      viewBox="0 0 506.4 506.4"
                      xmlSpace="preserve"
                      fill="#000000"
                      style={{ marginTop: '12px', marginBottom: '12px' }}
                    >
                      <g id="SVGRepo_bgCarrier" strokeWidth="0"></g>
                      <g id="SVGRepo_tracerCarrier" strokeLinecap="round" strokeLinejoin="round"></g>
                      <g id="SVGRepo_iconCarrier">
                        <circle style={{ fill: '#54B265' }} cx="253.2" cy="253.2" r="249.2" />
                        <path
                          style={{ fill: '#F4EFEF' }}
                          d="M372.8,200.4l-11.2-11.2c-4.4-4.4-12-4.4-16.4,0L232,302.4l-69.6-69.6c-4.4-4.4-12-4.4-16.4,0 L134.4,244c-4.4,4.4-4.4,12,0,16.4l89.2,89.2c4.4,4.4,12,4.4,16.4,0l0,0l0,0l10.4-10.4l0.8-0.8l121.6-121.6 C377.2,212.4,377.2,205.2,372.8,200.4z"
                        ></path>
                        <path d="M253.2,506.4C113.6,506.4,0,392.8,0,253.2S113.6,0,253.2,0s253.2,113.6,253.2,253.2S392.8,506.4,253.2,506.4z M253.2,8 C118,8,8,118,8,253.2s110,245.2,245.2,245.2s245.2-110,245.2-245.2S388.4,8,253.2,8z"></path>
                        <path d="M231.6,357.2c-4,0-8-1.6-11.2-4.4l-89.2-89.2c-6-6-6-16,0-22l11.6-11.6c6-6,16.4-6,22,0l66.8,66.8L342,186.4 c2.8-2.8,6.8-4.4,11.2-4.4c4,0,8,1.6,11.2,4.4l11.2,11.2l0,0c6,6,6,16,0,22L242.8,352.4C239.6,355.6,235.6,357.2,231.6,357.2z M154,233.6c-2,0-4,0.8-5.6,2.4l-11.6,11.6c-2.8,2.8-2.8,8,0,10.8l89.2,89.2c2.8,2.8,8,2.8,10.8,0l132.8-132.8c2.8-2.8,2.8-8,0-10.8 l-11.2-11.2c-2.8-2.8-8-2.8-10.8,0L234.4,306c-1.6,1.6-4,1.6-5.6,0l-69.6-69.6C158,234.4,156,233.6,154,233.6z"></path>
                      </g>
                    </svg>
                  </div>
                ) : (

                  <ColorRing className={styles['receipt-logo']} />
                )}


                <div className={styles['receipt-info']}>
                  {deviceType == 'clerk' ?
                    <h3>{transaction.confirmed === 1 && !transaction.is_paid ? (
                      "Silahkan Cek Pembayaran"
                    ) : transaction.confirmed === -1 && !transaction.is_paid ? (
                      "Dibatalkan Oleh Kasir"
                    ) : transaction.confirmed === -2 && !transaction.is_paid ? (
                      "Dibatalkan Oleh Pelanggan"
                    ) : transaction.confirmed === 2 && !transaction.is_paid ? (
                      "Sedang Diproses"
                    ) : transaction.confirmed === 3 || transaction.is_paid ? (
                      "Transaksi Sukses"
                    ) : (
                      "Silahkan Cek Ketersediaan"
                    )}</h3>
                    :
                    <h3>{transaction.confirmed === 1 ? (
                      (transaction.payment_type == 'cash' ? 'Silahkan Bayar Ke Kasir' : "Silahkan Bayar Dengan QRIS")
                    ) : transaction.confirmed === -1 ? (
                      "Dibatalkan Oleh Kasir"
                    ) : transaction.confirmed === -2 ? (
                      "Dibatalkan Oleh Pelanggan"
                    ) : transaction.confirmed === 2 ? (
                      "Sedang diproses"
                    ) : transaction.confirmed === 3 ? (
                      "Transaksi Sukses"
                    ) : (
                      "Memeriksa Ketersediaan "
                    )}</h3>}

                  <p>Transaction ID: {transaction.transactionId}</p>
                  <p>Payment Type: {transaction.payment_type}</p>
                  <p>{dayjs.utc(transaction.createdAt).tz(shop.timezone).format('YYYY-MM-DD HH:mm:ss')}</p>
                </div>
              </div>
              <div className={styles['dotted-line']}>
                <div className={styles['circle-left']}>

                </div>
                <div className={styles['line']} ></div>
                <div className={styles['circle-right']} >

                </div>
              </div>

              {transaction.paymentClaimed && transaction.confirmed < 2 && (
                <div className={styles.RibbonBanner}>
                  <img src={"https://i.imgur.com/yt6osgL.png"}></img>
                  <h1>payment claimed</h1>
                </div>
              )}
              <ul>
                {transaction.DetailedTransactions.map((detail) => (
                  <li key={detail.detailedTransactionId}>
                    <span>{detail.Item.name}</span> - {detail.qty < 1 ? 'tidak tersedia' : `${detail.qty} x Rp
                  ${detail.promoPrice ? detail.promoPrice : detail.price}`}
                  </li>
                ))}
              </ul>
              {!transaction.is_paid && transaction.confirmed > -1 &&
                <div
                  onClick={() => {
                    localStorage.setItem('lastTransaction', JSON.stringify(transaction));
                    setModal("message", { captMessage: 'Silahkan tambahkan pesanan', descMessage: 'Pembayaran akan ditambahkan ke transaksi sebelumnya.' }, null, null);

                    // Dispatch the custom event
                    window.dispatchEvent(new Event("localStorageUpdated"));
                  }}
                  className={styles["addNewItem"]}
                >
                  Tambah pesanan
                </div>
              }
              <h2 className={styles["Transactions-detail"]}>
                {transaction.serving_type === "pickup"
                  ? "Self pickup"
                  : `Serve to ${transaction.Table ? transaction.Table.tableNo : "N/A"
                  }`}
              </h2>

              {transaction.notes && (
                <>
                  <div className={styles.NoteContainer}>
                    <span>Note :</span>
                    <span></span>
                  </div>

                  <div className={styles.NoteContainer}>
                    <textarea
                      className={styles.NoteInput}
                      value={transaction.notes}
                      disabled
                    />
                  </div>
                </>
              )}

              <div className={styles.TotalContainer}>
                <span>Total:</span>
                <span>
                  Rp {calculateTotalPrice(transaction.DetailedTransactions)}
                </span>
              </div>

              <div className={styles.TotalContainer}>
                {(deviceType == 'clerk' && !transaction.is_paid && (transaction.confirmed == 0 || transaction.confirmed == 1 || transaction.confirmed == 2)) &&
                  <button
                    className={styles.PayButton}
                    onClick={() => handleConfirm(transaction.transactionId)}
                    disabled={isPaymentLoading}
                  >
                    {
                      isPaymentLoading ? (
                        <ColorRing height="50" width="50" color="white" />
                      ) : transaction.confirmed === 1 ? (
                        "Konfirmasi Telah Bayar"
                      ) : transaction.confirmed === 2 ? (
                        "Confirm item is ready"
                      ) : (
                        "Confirm availability"
                      )
                    }

                  </button>
                }

                {deviceType == 'guestDevice' && transaction.confirmed < 2 && transaction.payment_type != 'cash' && transaction.payment_type != 'paylater/cash' &&
                  <ButtonWithReplica
                    paymentUrl={paymentUrl}
                    price={
                      "Rp" + calculateTotalPrice(transaction.DetailedTransactions)
                    }
                    disabled={isPaymentLoading}
                    isPaymentLoading={isPaymentLoading}
                    handleClick={() => handleConfirm(transaction.transactionId)}
                    Open={() => setIsPaymentOpen(transaction.transactionId)}
                    isPaymentOpen={isPaymentOpen == transaction.transactionId}
                  >
                    {
                      isPaymentLoading ? null : isPaymentOpen == transaction.transactionId ? (
                        transaction.paymentClaimed ? (
                          <>
                            <div style={{ position: 'absolute', left: '15px', top: '9px' }}>
                              <ColorRing height="20" width="20" className={styles['receipt-logo']} />
                            </div>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Menunggu konfirmasi
                          </>
                        ) : 'Klaim telah bayar'
                      ) : 'Tampilkan QR'
                    }

                  </ButtonWithReplica>
                }
              </div>

              {deviceType == 'guestDevice' && transaction.confirmed >= 0 && transaction.confirmed < 2 && transaction.payment_type == 'cash' ?
                <button
                  className={styles.PayButton}
                  onClick={() => handleDecline(transaction.transactionId)}
                  disabled={
                    transaction.confirmed === -1 ||
                    transaction.confirmed === 3 ||
                    isPaymentLoading
                  } // Disable button if confirmed (1) or declined (-1) or
                >
                  {isPaymentLoading ? (
                    <ColorRing height="50" width="50" color="white" />
                  ) : transaction.confirmed === -1 ? (
                    "Ditolak" // Display "Declined" if the transaction is declined (-1)
                  ) : transaction.confirmed === -2 ? (
                    "Dibatalkan" // Display "Declined" if the transaction is declined (-1)
                  ) : (
                    "Batalkan" // Display "Confirm availability" if the transaction is not confirmed (0)
                  )}
                </button>
                :
                ((transaction.confirmed >= 0 && transaction.confirmed < 2 && transaction.payment_type != 'paylater/cash' && transaction.payment_type != 'paylater/cashless' || isPaymentOpen) &&
                  <h5
                    className={`${styles.DeclineButton}`}
                    onClick={() =>
                      isPaymentOpen
                        ? setIsPaymentOpen(false)
                        : handleDecline(transaction.transactionId)
                    }
                  >
                    {isPaymentOpen ? "kembali" : "batalkan"}
                  </h5>
                )
              }
            </div>
          ))}
      </div>
    </div>
  );
}
