import React, { useState } from "react";
import {
  ArrowLeft,
  ArrowRightLeft,
  ChevronDown,
  CircleStop,
  CircleStopIcon,
  Copy,
  Check,
  ExternalLink,
} from "lucide-react";
import { MultiTransactionType, OverallStatus } from "../types/activity";
import { getNetworkName, NETWORK_LOGO_URLS } from "./utils";

interface TransactionDetail {
  txnURL?: string;
  error?: string;
  status: OverallStatus;
}

interface ActivityDetailsProps {
  activity: any;
  onBack: () => void;
}

function getStatusColor(status: OverallStatus) {
  switch (status) {
    case OverallStatus.COMPLETED:
      return { color: "#027A48", background: "#ECFDF3" };
    case OverallStatus.PENDING:
      return { color: "#B54708", background: "#FFFAEB" };
    case OverallStatus.FAILED:
      return { color: "#B42318", background: "#FEF3F2" };
    default:
      return { color: "#344054", background: "#F2F4F7" };
  }
}

function formatDate(timestamp: number) {
  return new Date(timestamp).toLocaleString("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric",
    hour: "numeric",
    minute: "2-digit",
    hour12: true,
  });
}

function formatAmount(amount: string) {
  const num = parseFloat(amount);
  const decimalPlaces = amount.split(".")[1]?.length || 0;
  return decimalPlaces > 6 ? num.toFixed(6) : amount;
}

function truncateAddress(address: string) {
  if (!address) return "";
  return address.length > 10
    ? `${address.slice(0, 6)}...${address.slice(-4)}`
    : address;
}

export default function ActivityDetails({
  activity,
  onBack,
}: ActivityDetailsProps) {
  const [expandedTxIds, setExpandedTxIds] = useState<string[]>([]);
  const [copiedFrom, setCopiedFrom] = useState(false);
  const [copiedTo, setCopiedTo] = useState(false);

  const toggleTxDetails = (txId: string) => {
    setExpandedTxIds((prev) =>
      prev.includes(txId) ? prev.filter((id) => id !== txId) : [...prev, txId]
    );
  };

  const handleCopy = async (text: string, isSender: boolean) => {
    await navigator.clipboard.writeText(text);
    if (isSender) {
      setCopiedFrom(true);
      setTimeout(() => setCopiedFrom(false), 2000);
    } else {
      setCopiedTo(true);
      setTimeout(() => setCopiedTo(false), 2000);
    }
  };

  const firstSourceChain = activity.sourceChains[0]?.toString();
  const firstDestChain = activity.destinationChains[0]?.toString();
  const inputToken =
    activity.transactionType === MultiTransactionType.SWAP
      ? activity.metadata.tokenDetails.inputToken
      : activity.metadata.tokenDetails.token;
  const outputToken = activity.metadata.tokenDetails.outputToken;
  const statusStyle = getStatusColor(activity.metadata.status);

  console.log(activity);

  return (
    <div
      className="activity-details"
      style={{
        fontFamily: "Inter, sans-serif",
        width: "450px",
        height: "100%",
      }}
    >
      {/* Header */}
      <div
        style={{
          display: "flex",
          alignItems: "center",
          marginBottom: "24px",
          justifyContent: "space-between",
        }}
      >
        <button
          onClick={onBack}
          style={{
            background: "none",
            border: "none",
            cursor: "pointer",
            padding: "8px",
            marginRight: "8px",
          }}
        >
          <ArrowLeft size={24} />
        </button>
        <h1 style={{ margin: 0, fontSize: "20px", fontWeight: 600 }}>
          {activity.transactionType === MultiTransactionType.SWAP
            ? "Swap details"
            : "Transfer details"}
        </h1>
        <div style={{ width: "24px" }}></div>
      </div>

      {/* Swap Information */}
      <div
        style={{
          background: "#F4F6FF",
          borderRadius: "16px",
          padding: "24px",
          marginBottom: "12px",
        }}
      >
        {activity.transactionType === MultiTransactionType.SWAP ? (
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              gap: "12px",
            }}
          >
            <div
              style={{
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
                width: "90%",
              }}
            >
              <div
                style={{ marginBottom: "8px", width: "35px", height: "35px" }}
              >
                {inputToken?.logoURI ? (
                  <img
                    src={inputToken?.logoURI}
                    alt={`${inputToken?.tokenSymbol} logo`}
                    style={{
                      width: "100%",
                      height: "100%",
                      borderRadius: "50%",
                    }}
                  />
                ) : (
                  <CircleStopIcon size={35} />
                )}
              </div>
              <div
                style={{
                  color: "#535862",
                  marginBottom: "8px",
                  fontSize: "12px",
                }}
              >
                You Pay
              </div>
              <div
                style={{
                  fontSize: "20px",
                  fontWeight: 600,
                  textAlign: "center",
                }}
              >
                {formatAmount(activity.metadata.totalInputAmount.toString())}{" "}
                {inputToken?.tokenSymbol}
              </div>
            </div>
            <div
              style={{
                width: "58px",
                height: "28px",
                background: "white",
                borderRadius: "6px",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                border: "1px solid #D5D7DA",
              }}
            >
              <ArrowRightLeft size={16} />
            </div>
            <div
              style={{
                textAlign: "center",
                width: "90%",
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
              }}
            >
              <div
                style={{ marginBottom: "8px", width: "35px", height: "35px" }}
              >
                {outputToken?.logoURI ? (
                  <img
                    src={outputToken?.logoURI}
                    alt={`${outputToken?.tokenSymbol} logo`}
                    style={{
                      width: "100%",
                      height: "100%",
                      borderRadius: "50%",
                    }}
                  />
                ) : (
                  <CircleStopIcon size={35} />
                )}
              </div>
              <div
                style={{
                  color: "#535862",
                  marginBottom: "8px",
                  fontSize: "12px",
                }}
              >
                You Receive
              </div>
              <div style={{ fontSize: "20px", fontWeight: 600 }}>
                {formatAmount(activity.metadata.totalOutputAmount.toString())}{" "}
                {outputToken?.tokenSymbol}
              </div>
            </div>
          </div>
        ) : (
          <div
            style={{
              display: "flex",
              flexDirection: "column",
              gap: "12px",
              alignItems: "center",
            }}
          >
            {activity.metadata.tokenDetails.token?.logoURI ? (
              <div style={{ width: "44px", height: "44px" }}>
                <img
                  src={activity.metadata.tokenDetails.token?.logoURI}
                  alt={`${activity.metadata.tokenDetails.token?.tokenSymbol} logo`}
                  style={{ width: "100%", height: "100%", borderRadius: "50%" }}
                />
              </div>
            ) : (
              <CircleStopIcon size={35} />
            )}
            <div style={{ fontSize: "48px", fontWeight: 600 }}>
              {formatAmount(activity.metadata.totalInputAmount.toString())}{" "}
              {activity.metadata.tokenDetails.token?.tokenSymbol}
            </div>
          </div>
        )}
        <div
          style={{
            textAlign: "center",
            marginTop: "16px",
          }}
        >
          <span
            style={{
              padding: "2px 8px",
              borderRadius: "16px",
              fontSize: "12px",
              ...statusStyle,
              fontWeight: 500,
              textTransform: "capitalize",
            }}
          >
            {activity.metadata.status.toLowerCase()}
          </span>
        </div>
      </div>

      {activity.transactionType === MultiTransactionType.TRANSFER && (
        <div style={{ margin: "24px 0" }}>
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              background: "#F9FAFB",
              padding: "24px",
              borderRadius: "12px",
            }}
          >
            <div style={{ flex: 1, textAlign: "center" }}>
              <div
                style={{
                  color: "#667085",
                  fontSize: "16px",
                  marginBottom: "8px",
                }}
              >
                From
              </div>
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: "8px",
                  color: "#414651",
                  fontSize: "16px",
                  fontWeight: 500,
                  justifyContent: "center",
                }}
              >
                {truncateAddress(activity.sender.username)}
                <button
                  onClick={() =>
                    handleCopy(activity.sender.walletAddress, true)
                  }
                  style={{
                    background: "none",
                    border: "none",
                    padding: 0,
                    cursor: "pointer",
                    display: "flex",
                    alignItems: "center",
                  }}
                >
                  {copiedFrom ? (
                    <Check size={16} color="#027A48" />
                  ) : (
                    <Copy size={16} color="#667085" />
                  )}
                </button>
              </div>
            </div>

            <div
              style={{ width: "1px", background: "#EAECF0", margin: "0 24px" }}
            />

            <div style={{ flex: 1, textAlign: "center" }}>
              <div
                style={{
                  color: "#667085",
                  fontSize: "16px",
                  marginBottom: "8px",
                }}
              >
                Recipient
              </div>
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: "8px",
                  color: "#414651",
                  fontSize: "16px",
                  fontWeight: 500,
                  justifyContent: "center",
                }}
              >
                {truncateAddress(activity.receivers[0].walletAddress)}
                <button
                  onClick={() =>
                    handleCopy(activity.receivers[0].walletAddress, false)
                  }
                  style={{
                    background: "none",
                    border: "none",
                    padding: 0,
                    cursor: "pointer",
                    display: "flex",
                    alignItems: "center",
                  }}
                >
                  {copiedTo ? (
                    <Check size={16} color="#027A48" />
                  ) : (
                    <Copy size={16} color="#667085" />
                  )}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      <div
        style={{
          margin: "24px 0px",
          msOverflowStyle: "none",
          scrollbarWidth: "none",
        }}
      >
        <span style={{ fontSize: "14px", fontWeight: 600 }}>
          Payment source networks
        </span>

        <div
          style={{
            display: "flex",
            flexDirection: "column",
            gap: "12px",
            border: "1px solid #3662E3",
            borderRadius: "12px",
            padding: "12px",
            background: "#EBF0FF",
            margin: "12px 0",
          }}
        >
          {/* Transaction Links */}
          {Object.entries(
            activity.transactions as Record<string, TransactionDetail>
          ).map(([chainId, txDetails]) => (
            <div
              key={chainId}
              style={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
                flexDirection: "column",
                background: "white",
                borderRadius: "12px",
                border: "1px solid #D5D7DA",
                width: "100%",
              }}
            >
              <div
                style={{
                  display: "flex",
                  justifyContent: "space-between",
                  alignItems: "center",
                  width: "100%",
                  padding: "12px",
                  cursor:
                    txDetails.status === "COMPLETED" ? "pointer" : "default",
                }}
                onClick={() => {
                  if (txDetails.status === "COMPLETED") {
                    toggleTxDetails(chainId);
                  }
                }}
              >
                <div
                  style={{
                    display: "flex",
                    gap: "12px",
                    alignItems: "center",
                  }}
                >
                  <div style={{ width: "44px", height: "44px" }}>
                    <img
                      src={NETWORK_LOGO_URLS[chainId]}
                      alt={
                        activity.metadata.tokenDetails.inputToken?.tokenSymbol
                      }
                      style={{
                        width: "100%",
                        height: "100%",
                        borderRadius: "10%",
                      }}
                    />
                  </div>
                  <div>
                    <div
                      style={{
                        fontWeight: 500,
                        fontSize: "16px",
                        color: "#414651",
                        marginBottom: "6px",
                      }}
                    >
                      {getNetworkName(chainId)}
                    </div>
                    <div style={{ color: "#535862", fontSize: "12px" }}>
                      {
                        activity.metadata.inputAmounts[chainId][0]
                          ?.amountFormatted
                      }{" "}
                      {activity.metadata.inputAmounts[chainId][0]?.tokenSymbol}
                    </div>
                  </div>
                </div>
                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: "4px",
                  }}
                >
                  <span
                    style={{
                      ...getStatusColor(txDetails?.status as OverallStatus),
                      fontSize: "12px",
                      fontWeight: 500,
                      padding: "2px 8px",
                      borderRadius: "16px",
                      display: "flex",
                      alignItems: "center",
                      gap: "4px",
                      textTransform: "capitalize",
                    }}
                  >
                    {txDetails?.status?.toLowerCase()}
                  </span>
                  {txDetails.status === "COMPLETED" && (
                    <ChevronDown
                      size={16}
                      color="#667085"
                      style={{
                        transform: expandedTxIds.includes(chainId)
                          ? "rotate(180deg)"
                          : "rotate(0deg)",
                        transition: "transform 0.2s ease-in-out",
                      }}
                    />
                  )}
                </div>
              </div>

              {/* Transaction Details Section - Only shown for COMPLETED transactions */}
              {txDetails.status === "COMPLETED" &&
                expandedTxIds.includes(chainId) &&
                txDetails.txnURL && (
                  <div
                    style={{
                      width: "100%",
                      padding: "12px",
                      borderTop: "1px solid #EAECF0",
                      display: "flex",
                      flexDirection: "column",
                      gap: "8px",
                    }}
                  >
                    <div
                      style={{
                        display: "flex",
                        justifyContent: "space-between",
                        alignItems: "center",
                      }}
                    >
                      <span style={{ color: "#667085", fontSize: "14px" }}>
                        Explorer link
                      </span>
                      <a
                        href={txDetails.txnURL}
                        target="_blank"
                        rel="noopener noreferrer"
                        style={{
                          color: "#3662E3",
                          textDecoration: "none",
                          display: "flex",
                          alignItems: "center",
                          gap: "4px",
                          fontSize: "14px",
                        }}
                      >
                        View on {getNetworkName(chainId)}
                        <ExternalLink size={14} />
                      </a>
                    </div>
                  </div>
                )}
            </div>
          ))}
        </div>
        <div style={{ marginTop: "24px" }}>
          <span
            style={{ fontSize: "14px", fontWeight: 600, marginTop: "12px" }}
          >
            Payment destination networks
          </span>
        </div>
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            gap: "12px",
            border: "1px solid #3662E3",
            borderRadius: "12px",
            padding: "12px",
            background: "#EBF0FF",
            margin: "12px 0",
          }}
        >
          {Object.entries(
            activity.outputTokens as Record<
              string,
              Array<{
                amount: string;
                amountFormatted: string;
                tokenAddress: string;
                tokenName: string;
                tokenSymbol: string;
                receiver: {
                  username: string;
                  walletAddress: string;
                  solana_program_wallet: string;
                  ens: string;
                };
              }>
            >
          ).map(([chainId, tokens]) => {
            const token = tokens[0]; // Since we know there's only one token per chain in destination
            return (
              <div
                key={chainId}
                style={{
                  display: "flex",
                  justifyContent: "space-between",
                  alignItems: "center",
                  flexDirection: "column",
                  background: "white",
                  borderRadius: "12px",
                  border: "1px solid #D5D7DA",
                  width: "100%",
                }}
              >
                <div
                  style={{
                    display: "flex",
                    justifyContent: "space-between",
                    alignItems: "center",
                    width: "100%",
                    padding: "12px",
                    cursor: "pointer",
                  }}
                  onClick={() => toggleTxDetails(chainId)}
                >
                  <div
                    style={{
                      display: "flex",
                      gap: "12px",
                      alignItems: "center",
                    }}
                  >
                    <div style={{ width: "44px", height: "44px" }}>
                      <img
                        src={NETWORK_LOGO_URLS[chainId]}
                        alt={
                          activity.metadata.tokenDetails.outputToken
                            ?.tokenSymbol
                        }
                        style={{
                          width: "100%",
                          height: "100%",
                          borderRadius: "10%",
                        }}
                      />
                    </div>
                    <div>
                      <div
                        style={{
                          fontWeight: 500,
                          fontSize: "16px",
                          color: "#414651",
                          marginBottom: "6px",
                        }}
                      >
                        {getNetworkName(chainId)}
                      </div>
                      <div style={{ color: "#535862", fontSize: "12px" }}>
                        {formatAmount(token.amountFormatted)}{" "}
                        {token?.tokenSymbol}
                      </div>
                    </div>
                  </div>
                  <div
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: "4px",
                    }}
                  >
                    <span
                      style={{
                        ...getStatusColor(
                          activity.metadata.status as OverallStatus
                        ),
                        fontSize: "12px",
                        fontWeight: 500,
                        padding: "2px 8px",
                        borderRadius: "16px",
                        display: "flex",
                        alignItems: "center",
                        gap: "4px",
                        textTransform: "capitalize",
                      }}
                    >
                      {activity.metadata.status.toLowerCase()}
                    </span>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
        <div
          style={{
            background: "#F9F9F9",
            padding: "12px",
            borderRadius: "8px",
            display: "flex",
            flexDirection: "column",
            gap: "12px",
            marginBottom: "24px",
          }}
        >
          <div
            style={{
              display: "flex",
              gap: "12px",
              justifyContent: "space-between",
            }}
          >
            <div style={{ fontSize: "16px" }}>Date and Time</div>
            <div style={{ color: "#535862", fontSize: "16px" }}>
              {formatDate(activity.metadata.lastUpdatedTimestamp)}
            </div>
          </div>

          <div
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              padding: "16px 0",
              borderTop: "1px solid #EAECF0",
            }}
          >
            <span style={{ fontSize: "16px", fontWeight: 600 }}>Total</span>
            <span
              style={{ fontSize: "16px", fontWeight: 400, color: "#535862" }}
            >
              {activity.metadata.totalInputAmount} {inputToken?.tokenSymbol}
            </span>
          </div>
        </div>
      </div>
    </div>
  );
}
