"use client";

import { useEffect, useState, useCallback, CSSProperties } from "react";
import { Permission } from "../../auth-context";
import { adminApi } from "../../api";
import { Header } from "../../components/Header";
import { SatsDisplay } from "../../components/SatsDisplay";
import { StatusBadge } from "../../components/StatusBadge";
import { EmptyState } from "../../components/EmptyState";
import { ConfirmationButton } from "../../components/ConfirmationButton";
import { useRequireAuth } from "../../hooks/useRequireAuth";
import { components } from "../../generated/api";
import { formatDateTime } from "../../utils/date";
import { formatEur } from "../../utils/exchange";
import { layoutStyles, typographyStyles, bannerStyles, tradeCardStyles } from "../../styles/shared";

type AdminExchangeResponse = components["schemas"]["AdminExchangeResponse"];

type Tab = "upcoming" | "past";

export default function AdminTradesPage() {
  const { user, isLoading, isAuthorized } = useRequireAuth({
    requiredPermission: Permission.VIEW_ALL_EXCHANGES,
    fallbackRedirect: "/",
  });

  const [activeTab, setActiveTab] = useState<Tab>("upcoming");
  const [upcomingTrades, setUpcomingTrades] = useState<AdminExchangeResponse[]>([]);
  const [pastTrades, setPastTrades] = useState<AdminExchangeResponse[]>([]);
  const [isLoadingTrades, setIsLoadingTrades] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Action state - use Set to track multiple concurrent actions
  const [actioningIds, setActioningIds] = useState<Set<string>>(new Set());
  const [confirmAction, setConfirmAction] = useState<{
    id: string;
    type: "complete" | "no_show" | "cancel";
  } | null>(null);

  // Past trades filters
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [userSearch, setUserSearch] = useState("");

  const fetchUpcomingTrades = useCallback(async (): Promise<string | null> => {
    try {
      const data = await adminApi.getUpcomingTrades();
      setUpcomingTrades(data);
      return null;
    } catch (err) {
      console.error("Failed to fetch upcoming trades:", err);
      return "Failed to load upcoming trades";
    }
  }, []);

  const fetchPastTrades = useCallback(async (): Promise<string | null> => {
    try {
      const params: { status?: string; user_search?: string } = {};
      if (statusFilter !== "all") {
        params.status = statusFilter;
      }
      if (userSearch.trim()) {
        params.user_search = userSearch.trim();
      }

      const data = await adminApi.getPastTrades(
        Object.keys(params).length > 0 ? params : undefined
      );
      setPastTrades(data);
      return null;
    } catch (err) {
      console.error("Failed to fetch past trades:", err);
      return "Failed to load past trades";
    }
  }, [statusFilter, userSearch]);

  useEffect(() => {
    if (user && isAuthorized) {
      setIsLoadingTrades(true);
      setError(null);
      Promise.all([fetchUpcomingTrades(), fetchPastTrades()])
        .then(([upcomingErr, pastErr]) => {
          // Combine errors if both failed
          const errors = [upcomingErr, pastErr].filter(Boolean);
          if (errors.length > 0) {
            setError(errors.join("; "));
          }
        })
        .finally(() => {
          setIsLoadingTrades(false);
        });
    }
  }, [user, isAuthorized, fetchUpcomingTrades, fetchPastTrades]);

  const handleAction = async (publicId: string, action: "complete" | "no_show" | "cancel") => {
    // Add this trade to the set of actioning trades
    setActioningIds((prev) => new Set(prev).add(publicId));
    setError(null);

    try {
      if (action === "complete") {
        await adminApi.completeTrade(publicId);
      } else if (action === "no_show") {
        await adminApi.noShowTrade(publicId);
      } else if (action === "cancel") {
        await adminApi.cancelTrade(publicId);
      }
      // Refetch trades - errors from fetch are informational, not critical
      const [upcomingErr, pastErr] = await Promise.all([fetchUpcomingTrades(), fetchPastTrades()]);
      const fetchErrors = [upcomingErr, pastErr].filter(Boolean);
      if (fetchErrors.length > 0) {
        setError(fetchErrors.join("; "));
      }
      setConfirmAction(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : `Failed to ${action} trade`);
    } finally {
      // Remove this trade from the set of actioning trades
      setActioningIds((prev) => {
        const next = new Set(prev);
        next.delete(publicId);
        return next;
      });
    }
  };

  if (isLoading) {
    return (
      <main style={layoutStyles.main}>
        <div style={layoutStyles.loader}>Loading...</div>
      </main>
    );
  }

  if (!isAuthorized) {
    return null;
  }

  const trades = activeTab === "upcoming" ? upcomingTrades : pastTrades;

  return (
    <main style={layoutStyles.main}>
      <Header currentPage="admin-trades" />
      <div style={styles.content}>
        <h1 style={typographyStyles.pageTitle}>Trades</h1>
        <p style={typographyStyles.pageSubtitle}>Manage Bitcoin exchange trades</p>

        {error && <div style={bannerStyles.errorBanner}>{error}</div>}

        {/* Tabs */}
        <div style={styles.tabRow}>
          <button
            onClick={() => setActiveTab("upcoming")}
            style={{
              ...styles.tabButton,
              ...(activeTab === "upcoming" ? styles.tabButtonActive : {}),
            }}
          >
            Upcoming ({upcomingTrades.length})
          </button>
          <button
            onClick={() => setActiveTab("past")}
            style={{
              ...styles.tabButton,
              ...(activeTab === "past" ? styles.tabButtonActive : {}),
            }}
          >
            History ({pastTrades.length})
          </button>
        </div>

        {/* Filters for Past tab */}
        {activeTab === "past" && (
          <div style={styles.filterRow}>
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
              style={styles.filterSelect}
            >
              <option value="all">All Statuses</option>
              <option value="completed">Completed</option>
              <option value="no_show">No Show</option>
              <option value="cancelled_by_user">User Cancelled</option>
              <option value="cancelled_by_admin">Admin Cancelled</option>
            </select>
            <input
              type="text"
              placeholder="Search by email..."
              value={userSearch}
              onChange={(e) => setUserSearch(e.target.value)}
              style={styles.searchInput}
            />
          </div>
        )}

        {isLoadingTrades ? (
          <EmptyState message="Loading trades..." isLoading={true} />
        ) : trades.length === 0 ? (
          <EmptyState
            message={activeTab === "upcoming" ? "No upcoming trades." : "No trades found."}
          />
        ) : (
          <div style={tradeCardStyles.tradeList}>
            {trades.map((trade) => {
              const isBuy = trade.direction === "buy";
              const isPast = new Date(trade.slot_start) <= new Date();
              const canComplete = trade.status === "booked" && isPast && activeTab === "past";

              return (
                <div key={trade.id} style={tradeCardStyles.tradeCard}>
                  <div style={tradeCardStyles.tradeHeader}>
                    <div style={tradeCardStyles.tradeInfo}>
                      <div style={tradeCardStyles.tradeTime}>
                        {formatDateTime(trade.slot_start)}
                      </div>

                      {/* User Info */}
                      <div style={styles.userInfo}>
                        <span style={styles.userEmail}>{trade.user_email}</span>
                        {trade.user_contact.telegram && (
                          <span style={styles.contactBadge}>{trade.user_contact.telegram}</span>
                        )}
                        {trade.user_contact.signal && (
                          <span style={styles.contactBadge}>
                            Signal: {trade.user_contact.signal}
                          </span>
                        )}
                      </div>

                      {/* Trade Details */}
                      <div style={tradeCardStyles.tradeDetails}>
                        <span
                          style={{
                            ...tradeCardStyles.directionBadge,
                            // Admin perspective: invert direction (if user buys, admin sells)
                            background: isBuy
                              ? "rgba(248, 113, 113, 0.15)"
                              : "rgba(74, 222, 128, 0.15)",
                            color: isBuy ? "#f87171" : "#4ade80",
                          }}
                        >
                          {isBuy ? "SELL BTC" : "BUY BTC"}
                        </span>
                        <span
                          style={{
                            ...tradeCardStyles.directionBadge,
                            background: "rgba(167, 139, 250, 0.15)",
                            color: "#a78bfa",
                          }}
                        >
                          {isBuy
                            ? `Send via ${trade.bitcoin_transfer_method === "onchain" ? "Onchain" : "Lightning"}`
                            : `Receive via ${trade.bitcoin_transfer_method === "onchain" ? "Onchain" : "Lightning"}`}
                        </span>
                        <span style={tradeCardStyles.amount}>{formatEur(trade.eur_amount)}</span>
                        <span style={tradeCardStyles.arrow}>↔</span>
                        <span style={tradeCardStyles.satsAmount}>
                          <SatsDisplay sats={trade.sats_amount} />
                        </span>
                      </div>

                      <div style={tradeCardStyles.rateRow}>
                        <span style={tradeCardStyles.rateLabel}>Rate:</span>
                        <span style={tradeCardStyles.rateValue}>
                          €
                          {trade.agreed_price_eur.toLocaleString("de-DE", {
                            maximumFractionDigits: 0,
                          })}
                          /BTC
                        </span>
                        <span style={tradeCardStyles.rateLabel}>Market:</span>
                        <span style={tradeCardStyles.rateValue}>
                          €
                          {trade.market_price_eur.toLocaleString("de-DE", {
                            maximumFractionDigits: 0,
                          })}
                        </span>
                      </div>

                      <StatusBadge tradeStatus={trade.status} style={{ marginTop: "0.5rem" }}>
                        {""}
                      </StatusBadge>
                    </div>

                    {/* Actions */}
                    <div style={styles.buttonGroup}>
                      {canComplete && (
                        <>
                          <ConfirmationButton
                            isConfirming={
                              confirmAction?.id === trade.public_id &&
                              confirmAction?.type === "complete"
                            }
                            onConfirm={() => handleAction(trade.public_id, "complete")}
                            onCancel={() => setConfirmAction(null)}
                            onActionClick={() =>
                              setConfirmAction({
                                id: trade.public_id,
                                type: "complete",
                              })
                            }
                            actionLabel="Complete"
                            isLoading={actioningIds.has(trade.public_id)}
                            confirmVariant="success"
                            confirmButtonStyle={styles.successButton}
                            actionButtonStyle={styles.successButton}
                          />
                          <ConfirmationButton
                            isConfirming={
                              confirmAction?.id === trade.public_id &&
                              confirmAction?.type === "no_show"
                            }
                            onConfirm={() => handleAction(trade.public_id, "no_show")}
                            onCancel={() => setConfirmAction(null)}
                            onActionClick={() =>
                              setConfirmAction({
                                id: trade.public_id,
                                type: "no_show",
                              })
                            }
                            actionLabel="No Show"
                            isLoading={actioningIds.has(trade.public_id)}
                            confirmVariant="primary"
                            actionButtonStyle={styles.warningButton}
                          />
                        </>
                      )}
                      {trade.status === "booked" && (
                        <ConfirmationButton
                          isConfirming={
                            confirmAction?.id === trade.public_id &&
                            confirmAction?.type === "cancel"
                          }
                          onConfirm={() => handleAction(trade.public_id, "cancel")}
                          onCancel={() => setConfirmAction(null)}
                          onActionClick={() =>
                            setConfirmAction({
                              id: trade.public_id,
                              type: "cancel",
                            })
                          }
                          actionLabel="Cancel"
                          isLoading={actioningIds.has(trade.public_id)}
                          confirmVariant="danger"
                          confirmButtonStyle={styles.dangerButton}
                        />
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </main>
  );
}

// Page-specific styles (trade card styles are shared via tradeCardStyles)
const styles: Record<string, CSSProperties> = {
  content: {
    flex: 1,
    padding: "2rem",
    maxWidth: "900px",
    margin: "0 auto",
    width: "100%",
  },
  tabRow: {
    display: "flex",
    gap: "0.5rem",
    marginBottom: "1.5rem",
  },
  tabButton: {
    fontFamily: "'DM Sans', system-ui, sans-serif",
    fontSize: "0.9rem",
    fontWeight: 500,
    padding: "0.75rem 1.5rem",
    background: "rgba(255, 255, 255, 0.03)",
    border: "1px solid rgba(255, 255, 255, 0.08)",
    borderRadius: "8px",
    color: "rgba(255, 255, 255, 0.6)",
    cursor: "pointer",
    transition: "all 0.2s",
  },
  tabButtonActive: {
    background: "rgba(167, 139, 250, 0.15)",
    border: "1px solid #a78bfa",
    color: "#a78bfa",
  },
  filterRow: {
    display: "flex",
    gap: "0.75rem",
    marginBottom: "1.5rem",
    flexWrap: "wrap",
  },
  filterSelect: {
    fontFamily: "'DM Sans', system-ui, sans-serif",
    padding: "0.5rem 1rem",
    background: "rgba(255, 255, 255, 0.05)",
    border: "1px solid rgba(255, 255, 255, 0.1)",
    borderRadius: "6px",
    color: "#fff",
    fontSize: "0.875rem",
  },
  searchInput: {
    fontFamily: "'DM Sans', system-ui, sans-serif",
    padding: "0.5rem 1rem",
    background: "rgba(255, 255, 255, 0.05)",
    border: "1px solid rgba(255, 255, 255, 0.1)",
    borderRadius: "6px",
    color: "#fff",
    fontSize: "0.875rem",
    minWidth: "200px",
  },
  // Admin-specific: user contact info
  userInfo: {
    display: "flex",
    alignItems: "center",
    gap: "0.5rem",
    marginBottom: "0.5rem",
    flexWrap: "wrap",
  },
  userEmail: {
    fontFamily: "'DM Sans', system-ui, sans-serif",
    fontSize: "0.875rem",
    color: "rgba(255, 255, 255, 0.7)",
  },
  contactBadge: {
    fontFamily: "'DM Mono', monospace",
    fontSize: "0.7rem",
    padding: "0.15rem 0.5rem",
    background: "rgba(99, 102, 241, 0.15)",
    border: "1px solid rgba(99, 102, 241, 0.3)",
    borderRadius: "4px",
    color: "rgba(129, 140, 248, 0.9)",
  },
  // Admin-specific: vertical button group
  buttonGroup: {
    display: "flex",
    flexDirection: "column",
    gap: "0.5rem",
    alignItems: "flex-end",
  },
  successButton: {
    fontFamily: "'DM Sans', system-ui, sans-serif",
    padding: "0.4rem 0.85rem",
    fontSize: "0.75rem",
    fontWeight: 500,
    background: "rgba(34, 197, 94, 0.2)",
    border: "1px solid rgba(34, 197, 94, 0.3)",
    borderRadius: "6px",
    color: "#4ade80",
    cursor: "pointer",
    transition: "all 0.2s",
  },
  warningButton: {
    fontFamily: "'DM Sans', system-ui, sans-serif",
    padding: "0.4rem 0.85rem",
    fontSize: "0.75rem",
    fontWeight: 500,
    background: "rgba(251, 146, 60, 0.2)",
    border: "1px solid rgba(251, 146, 60, 0.3)",
    borderRadius: "6px",
    color: "#fb923c",
    cursor: "pointer",
    transition: "all 0.2s",
  },
  dangerButton: {
    fontFamily: "'DM Sans', system-ui, sans-serif",
    padding: "0.4rem 0.85rem",
    fontSize: "0.75rem",
    fontWeight: 500,
    background: "rgba(239, 68, 68, 0.2)",
    border: "1px solid rgba(239, 68, 68, 0.3)",
    borderRadius: "6px",
    color: "#f87171",
    cursor: "pointer",
    transition: "all 0.2s",
  },
};
