"use client";

import { useEffect, useRef, useState } from "react";
import { getStoredUser } from "@/lib/utils/persistAuth";

interface Transaction {
  id: number;
  user_id: number;
  package_id: number;
  price: number;
  transaction_id: string;
  description: string;
  expiry_date: string;
  transaction_status: number; // 1 = success, 2 = failed/pending
  status: number;             // 1 = active, 0 = expired
  created_at: string;
  updated_at: string;
  package_name: string;
  package_price: number;
  data: string;
}

interface TransactionListResponse {
  status: number;
  message: string;
  result: Transaction[];
}

interface TransactionListModalProps {
  open: boolean;
  onClose: () => void;
}

function txStatusLabel(tx: Transaction): { label: string; color: string; bg: string } {
  if (tx.transaction_status === 2) {
    return { label: "Failed", color: "#C1272D", bg: "rgba(193,39,45,0.08)" };
  }
  if (tx.status === 1) {
    return { label: "Active", color: "#047857", bg: "rgba(4,120,87,0.08)" };
  }
  return { label: "Expired", color: "#6B7280", bg: "rgba(107,114,128,0.1)" };
}

function formatDate(dateStr: string) {
  const d = new Date(dateStr);
  return d.toLocaleDateString("en-IN", { day: "numeric", month: "short", year: "numeric" });
}

function truncateTxId(txId: string) {
  if (txId.length <= 20) return txId;
  return `${txId.slice(0, 8)}…${txId.slice(-8)}`;
}

export default function TransactionListModal({ open, onClose }: TransactionListModalProps) {
  const [visible, setVisible] = useState(false);
  const [transactions, setTransactions] = useState<Transaction[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const fetchedRef = useRef(false);

  useEffect(() => {
    if (open) {
      requestAnimationFrame(() => setVisible(true));
      if (!fetchedRef.current) {
        fetchedRef.current = true;
        loadTransactions();
      }
    } else {
      setVisible(false);
      fetchedRef.current = false;
    }
  }, [open]);

  async function loadTransactions() {
    const user = getStoredUser();
    if (!user?.id) {
      setError("Please log in to view transactions.");
      return;
    }
    setLoading(true);
    setError(null);
    try {
      const { default: apiClient } = await import("@/services/api.client");
      const { API_ENDPOINTS } = await import("@/lib/constants/apiEndpoints");
      const { data } = await apiClient.post<TransactionListResponse>(
        API_ENDPOINTS.GET_TRANSACTION_LIST,
        { user_id: user.id },
      );
      setTransactions(data.result ?? []);
    } catch {
      setError("Failed to load transactions.");
    } finally {
      setLoading(false);
    }
  }

  if (!open && !visible) return null;

  return (
    <>
      {/* Backdrop — sits above settings modal */}
      <div
        onClick={onClose}
        style={{
          position: "fixed", inset: 0,
          background: "rgba(14,14,17,0.35)",
          zIndex: 1050,
          opacity: visible ? 1 : 0,
          transition: "opacity 0.22s ease",
        }}
      />

      {/* Drawer — stacks on top of settings drawer */}
      <div
        style={{
          position: "fixed",
          top: 0, right: 0, bottom: 0,
          width: "min(420px, 100vw)",
          background: "var(--surf, #ffffff)",
          zIndex: 1051,
          display: "flex",
          flexDirection: "column",
          transform: visible ? "translateX(0)" : "translateX(100%)",
          transition: "transform 0.3s cubic-bezier(0.32,0.72,0,1)",
          boxShadow: "-8px 0 40px rgba(0,0,0,0.18)",
        }}
      >
        {/* ── Header ── */}
        <div style={{
          display: "flex", alignItems: "center", gap: "0.75rem",
          padding: "1.25rem 1.375rem",
          borderBottom: "1px solid var(--border, #e5e7eb)",
          flexShrink: 0,
          position: "sticky", top: 0,
          background: "var(--surf, #fff)", zIndex: 1,
        }}>
          <button
            onClick={onClose}
            style={{
              width: 32, height: 32, borderRadius: "50%",
              background: "var(--bg, #f8f9fb)",
              border: "1px solid var(--border, #e5e7eb)",
              display: "flex", alignItems: "center", justifyContent: "center",
              cursor: "pointer", flexShrink: 0,
              color: "var(--text-2, #6b7280)",
            }}
          >
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
              <path d="M19 12H5M11 6l-6 6 6 6" />
            </svg>
          </button>

          <div style={{ display: "flex", alignItems: "center", gap: "0.5rem", flex: 1 }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--ink, #0e0e11)" strokeWidth="2">
              <rect x="2" y="5" width="20" height="14" rx="2" />
              <path d="M2 10h20" />
            </svg>
            <h2 style={{ margin: 0, fontSize: "1rem", fontWeight: 800, color: "var(--ink, #0e0e11)" }}>
              Transactions
            </h2>
          </div>

          {transactions.length > 0 && (
            <span style={{
              fontSize: 11, fontFamily: "var(--mono, monospace)",
              fontWeight: 700, color: "var(--text-3, #9ca3af)",
              background: "var(--bg, #f8f9fb)",
              border: "1px solid var(--border, #e5e7eb)",
              borderRadius: 99, padding: "2px 8px",
            }}>
              {transactions.length}
            </span>
          )}
        </div>

        {/* ── Body ── */}
        <div style={{ flex: 1, overflowY: "auto", padding: "1.25rem 1.375rem 2rem" }}>

          {/* Loading skeleton */}
          {loading && (
            <div style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}>
              {Array.from({ length: 3 }).map((_, i) => (
                <div
                  key={i}
                  style={{
                    borderRadius: 12,
                    border: "1px solid var(--border, #e5e7eb)",
                    padding: "1rem",
                    background: "var(--surf, #fff)",
                    opacity: 1 - i * 0.2,
                  }}
                >
                  <div style={{ display: "flex", justifyContent: "space-between", marginBottom: "0.625rem" }}>
                    <div style={{ height: 11, width: "35%", background: "#e5e7eb", borderRadius: 4 }} />
                    <div style={{ height: 18, width: "18%", background: "#e5e7eb", borderRadius: 99 }} />
                  </div>
                  <div style={{ height: 20, width: "55%", background: "#e5e7eb", borderRadius: 4, marginBottom: "0.5rem" }} />
                  <div style={{ height: 10, width: "70%", background: "#e5e7eb", borderRadius: 4 }} />
                </div>
              ))}
            </div>
          )}

          {/* Error state */}
          {!loading && error && (
            <div style={{
              textAlign: "center", padding: "3rem 0",
              color: "var(--text-2, #6b7280)",
            }}>
              <div style={{
                width: 48, height: 48, borderRadius: "50%",
                background: "rgba(193,39,45,0.08)",
                display: "flex", alignItems: "center", justifyContent: "center",
                margin: "0 auto 0.875rem",
              }}>
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#C1272D" strokeWidth="2">
                  <circle cx="12" cy="12" r="10" />
                  <path d="M12 8v4M12 16h.01" />
                </svg>
              </div>
              <p style={{ fontWeight: 600, color: "var(--ink, #0e0e11)", marginBottom: "0.25rem" }}>{error}</p>
              <button
                onClick={loadTransactions}
                style={{
                  marginTop: "0.75rem",
                  padding: "0.4375rem 1.125rem",
                  background: "var(--brand, #C1272D)",
                  color: "#fff",
                  border: "none",
                  borderRadius: 8,
                  fontWeight: 700,
                  fontSize: "0.8125rem",
                  cursor: "pointer",
                }}
              >
                Retry
              </button>
            </div>
          )}

          {/* Empty state */}
          {!loading && !error && transactions.length === 0 && (
            <div style={{ textAlign: "center", padding: "3.5rem 0", color: "var(--text-2, #6b7280)" }}>
              <div style={{
                width: 56, height: 56, borderRadius: "50%",
                background: "var(--bg, #f8f9fb)",
                border: "1px solid var(--border, #e5e7eb)",
                display: "flex", alignItems: "center", justifyContent: "center",
                margin: "0 auto 0.875rem",
              }}>
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--text-3, #9ca3af)" strokeWidth="1.5">
                  <rect x="2" y="5" width="20" height="14" rx="2" />
                  <path d="M2 10h20" />
                </svg>
              </div>
              <p style={{ fontWeight: 700, color: "var(--ink, #0e0e11)", marginBottom: "0.25rem", fontSize: "0.9375rem" }}>
                No transactions yet
              </p>
              <p style={{ fontSize: "0.8125rem" }}>
                Your subscription payments will appear here
              </p>
            </div>
          )}

          {/* Transaction list */}
          {!loading && !error && transactions.length > 0 && (
            <div style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}>
              {transactions.map((tx, idx) => {
                const badge = txStatusLabel(tx);
                const isActive = tx.status === 1 && tx.transaction_status === 1;
                return (
                  <div
                    key={tx.id}
                    style={{
                      borderRadius: 12,
                      border: `1.5px solid ${isActive ? "rgba(4,120,87,0.2)" : "var(--border, #e5e7eb)"}`,
                      background: isActive
                        ? "linear-gradient(135deg, rgba(4,120,87,0.03) 0%, rgba(4,120,87,0.01) 100%)"
                        : "var(--surf, #fff)",
                      padding: "1rem 1.125rem",
                      position: "relative",
                      overflow: "hidden",
                      animation: `txSlideIn 0.3s ease ${idx * 0.06}s both`,
                    }}
                  >
                    {/* Active left accent bar */}
                    {isActive && (
                      <div style={{
                        position: "absolute", left: 0, top: 0, bottom: 0,
                        width: 3,
                        background: "#047857",
                        borderRadius: "0 0 0 12px",
                      }} />
                    )}

                    {/* Row 1: package name + status badge */}
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: "0.5rem" }}>
                      <div style={{ display: "flex", alignItems: "center", gap: "0.5rem" }}>
                        <span style={{
                          fontSize: "0.6875rem",
                          fontFamily: "var(--mono, monospace)",
                          fontWeight: 700,
                          letterSpacing: "0.08em",
                          textTransform: "uppercase",
                          color: "var(--text-3, #9ca3af)",
                        }}>
                          #{tx.id}
                        </span>
                        <span style={{
                          width: 3, height: 3, borderRadius: "50%",
                          background: "var(--text-3, #9ca3af)",
                          display: "inline-block",
                        }} />
                        <span style={{
                          fontSize: "0.6875rem",
                          fontFamily: "var(--mono, monospace)",
                          color: "var(--text-3, #9ca3af)",
                        }}>
                          {formatDate(tx.created_at)}
                        </span>
                      </div>
                      <span style={{
                        display: "inline-flex", alignItems: "center", gap: "0.3rem",
                        fontSize: "0.6875rem",
                        fontWeight: 700,
                        letterSpacing: "0.06em",
                        textTransform: "uppercase",
                        color: badge.color,
                        background: badge.bg,
                        borderRadius: 99,
                        padding: "3px 9px",
                        fontFamily: "var(--mono, monospace)",
                      }}>
                        {badge.label === "Active" && (
                          <span style={{
                            width: 5, height: 5, borderRadius: "50%",
                            background: "#047857",
                            display: "inline-block",
                          }} />
                        )}
                        {badge.label}
                      </span>
                    </div>

                    {/* Row 2: plan name + price */}
                    <div style={{ display: "flex", alignItems: "baseline", gap: "0.5rem", marginBottom: "0.5rem" }}>
                      <span style={{
                        fontWeight: 800,
                        fontSize: "0.9375rem",
                        color: "var(--ink, #0e0e11)",
                      }}>
                        {tx.package_name}
                      </span>
                      <span style={{
                        fontFamily: "var(--mono, monospace)",
                        fontWeight: 700,
                        fontSize: "0.875rem",
                        color: "var(--brand, #C1272D)",
                      }}>
                        ₹{tx.price}
                      </span>
                    </div>

                    {/* Row 3: transaction ID */}
                    <div style={{
                      fontFamily: "var(--mono, monospace)",
                      fontSize: "0.6875rem",
                      color: "var(--text-2, #6b7280)",
                      marginBottom: "0.4375rem",
                      letterSpacing: "0.03em",
                    }}>
                      TXN {truncateTxId(tx.transaction_id)}
                    </div>

                    {/* Row 4: expiry */}
                    <div style={{
                      display: "flex", alignItems: "center", gap: "0.375rem",
                      fontSize: "0.75rem",
                      color: "var(--text-2, #6b7280)",
                    }}>
                      <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ flexShrink: 0, opacity: 0.6 }}>
                        <rect x="3" y="4" width="18" height="18" rx="2" />
                        <path d="M16 2v4M8 2v4M3 10h18" />
                      </svg>
                      <span>
                        Expires{" "}
                        <span style={{ fontFamily: "var(--mono, monospace)", fontWeight: 600 }}>
                          {formatDate(tx.expiry_date)}
                        </span>
                      </span>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* ── Footer note ── */}
        <div style={{
          padding: "0.875rem 1.375rem",
          borderTop: "1px solid var(--border, #e5e7eb)",
          flexShrink: 0,
        }}>
          <p style={{
            margin: 0,
            fontSize: 11,
            color: "var(--text-3, #9ca3af)",
            fontFamily: "var(--mono, monospace)",
            textAlign: "center",
            lineHeight: 1.5,
          }}>
            Payments processed securely via DTNews
          </p>
        </div>
      </div>

      <style>{`
        @keyframes txSlideIn {
          from { opacity: 0; transform: translateY(10px); }
          to   { opacity: 1; transform: translateY(0); }
        }
      `}</style>
    </>
  );
}
