"use client";

import { CSSProperties, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { Permission } from "../../auth-context";
import { tradesApi } from "../../api";
import { Header } from "../../components/Header";
import { SatsDisplay } from "../../components/SatsDisplay";
import { StatusBadge } from "../../components/StatusBadge";
import { useRequireAuth } from "../../hooks/useRequireAuth";
import { useAsyncData } from "../../hooks/useAsyncData";
import { formatDateTime } from "../../utils/date";
import { formatEur } from "../../utils/exchange";
import {
  layoutStyles,
  typographyStyles,
  bannerStyles,
  buttonStyles,
  tradeCardStyles,
} from "../../styles/shared";

export default function TradeDetailPage() {
  const router = useRouter();
  const params = useParams();
  const publicId = params?.id as string | undefined;
  const [cancelError, setCancelError] = useState<string | null>(null);

  const { user, isLoading, isAuthorized } = useRequireAuth({
    requiredPermission: Permission.VIEW_OWN_EXCHANGES,
    fallbackRedirect: "/",
  });

  const {
    data: trade,
    isLoading: isLoadingTrade,
    error,
  } = useAsyncData(
    () => {
      if (!publicId) throw new Error("Trade ID is required");
      return tradesApi.getTrade(publicId);
    },
    {
      enabled: !!user && isAuthorized && !!publicId,
      onError: () => {
        // Error message is set by useAsyncData
      },
    }
  );

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

  if (!isAuthorized) {
    return null;
  }

  if (error || (!isLoadingTrade && !trade)) {
    return (
      <main style={layoutStyles.main}>
        <Header currentPage="trades" />
        <div style={styles.content}>
          <h1 style={typographyStyles.pageTitle}>Trade Details</h1>
          {error && (
            <div style={bannerStyles.errorBanner}>
              {error ||
                "Failed to load trade. It may not exist or you may not have permission to view it."}
            </div>
          )}
          <button onClick={() => router.push("/trades")} style={buttonStyles.primaryButton}>
            Back to Trades
          </button>
        </div>
      </main>
    );
  }

  if (!trade) {
    return null;
  }

  const isBuy = trade.direction === "buy";

  return (
    <main style={layoutStyles.main}>
      <Header currentPage="trades" />
      <div style={styles.content}>
        <div style={styles.header}>
          <h1 style={typographyStyles.pageTitle}>Trade Details</h1>
          <button onClick={() => router.push("/trades")} style={buttonStyles.secondaryButton}>
            ← Back to Trades
          </button>
        </div>

        <div style={styles.tradeDetailCard}>
          <div style={styles.detailSection}>
            <h2 style={styles.sectionTitle}>Trade Information</h2>
            <div style={styles.detailGrid}>
              <div style={styles.detailRow}>
                <span style={styles.detailLabel}>Status:</span>
                <StatusBadge tradeStatus={trade.status}>{""}</StatusBadge>
              </div>
              <div style={styles.detailRow}>
                <span style={styles.detailLabel}>Time:</span>
                <span style={styles.detailValue}>{formatDateTime(trade.slot_start)}</span>
              </div>
              <div style={styles.detailRow}>
                <span style={styles.detailLabel}>Direction:</span>
                <span
                  style={{
                    ...styles.detailValue,
                    color: isBuy ? "#4ade80" : "#f87171",
                    fontWeight: 600,
                  }}
                >
                  {isBuy ? "BUY BTC" : "SELL BTC"}
                </span>
              </div>
              <div style={styles.detailRow}>
                <span style={styles.detailLabel}>Payment Method:</span>
                <span style={styles.detailValue}>
                  {isBuy
                    ? `Receive via ${trade.bitcoin_transfer_method === "onchain" ? "Onchain" : "Lightning"}`
                    : `Send via ${trade.bitcoin_transfer_method === "onchain" ? "Onchain" : "Lightning"}`}
                </span>
              </div>
            </div>
          </div>

          <div style={styles.detailSection}>
            <h2 style={styles.sectionTitle}>Amounts</h2>
            <div style={styles.detailGrid}>
              <div style={styles.detailRow}>
                <span style={styles.detailLabel}>EUR Amount:</span>
                <span style={styles.detailValue}>{formatEur(trade.eur_amount)}</span>
              </div>
              <div style={styles.detailRow}>
                <span style={styles.detailLabel}>Bitcoin Amount:</span>
                <span style={{ ...styles.detailValue, ...tradeCardStyles.satsAmount }}>
                  <SatsDisplay sats={trade.sats_amount} />
                </span>
              </div>
            </div>
          </div>

          <div style={styles.detailSection}>
            <h2 style={styles.sectionTitle}>Pricing</h2>
            <div style={styles.detailGrid}>
              <div style={styles.detailRow}>
                <span style={styles.detailLabel}>Market Price:</span>
                <span style={styles.detailValue}>
                  €
                  {trade.market_price_eur.toLocaleString("de-DE", {
                    maximumFractionDigits: 0,
                  })}
                  /BTC
                </span>
              </div>
              <div style={styles.detailRow}>
                <span style={styles.detailLabel}>Agreed Price:</span>
                <span style={styles.detailValue}>
                  €
                  {trade.agreed_price_eur.toLocaleString("de-DE", {
                    maximumFractionDigits: 0,
                  })}
                  /BTC
                </span>
              </div>
              <div style={styles.detailRow}>
                <span style={styles.detailLabel}>Premium:</span>
                <span style={styles.detailValue}>{trade.premium_percentage}%</span>
              </div>
            </div>
          </div>

          <div style={styles.detailSection}>
            <h2 style={styles.sectionTitle}>Timestamps</h2>
            <div style={styles.detailGrid}>
              <div style={styles.detailRow}>
                <span style={styles.detailLabel}>Created:</span>
                <span style={styles.detailValue}>{formatDateTime(trade.created_at)}</span>
              </div>
              {trade.cancelled_at && (
                <div style={styles.detailRow}>
                  <span style={styles.detailLabel}>Cancelled:</span>
                  <span style={styles.detailValue}>{formatDateTime(trade.cancelled_at)}</span>
                </div>
              )}
              {trade.completed_at && (
                <div style={styles.detailRow}>
                  <span style={styles.detailLabel}>Completed:</span>
                  <span style={styles.detailValue}>{formatDateTime(trade.completed_at)}</span>
                </div>
              )}
            </div>
          </div>

          {cancelError && <div style={bannerStyles.errorBanner}>{cancelError}</div>}
          {trade.status === "booked" && (
            <div style={styles.actionSection}>
              <button
                onClick={async () => {
                  if (
                    !confirm(
                      "Are you sure you want to cancel this trade? This action cannot be undone."
                    )
                  ) {
                    return;
                  }
                  try {
                    await tradesApi.cancelTrade(trade.public_id);
                    router.push("/trades");
                  } catch (err) {
                    setCancelError(err instanceof Error ? err.message : "Failed to cancel trade");
                  }
                }}
                style={buttonStyles.secondaryButton}
              >
                Cancel Trade
              </button>
            </div>
          )}
        </div>
      </div>
    </main>
  );
}

const styles: Record<string, CSSProperties> = {
  content: {
    flex: 1,
    padding: "2rem",
    maxWidth: "800px",
    margin: "0 auto",
    width: "100%",
  },
  header: {
    display: "flex",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: "2rem",
  },
  tradeDetailCard: {
    background: "rgba(255, 255, 255, 0.03)",
    border: "1px solid rgba(255, 255, 255, 0.08)",
    borderRadius: "12px",
    padding: "2rem",
  },
  detailSection: {
    marginBottom: "2rem",
  },
  sectionTitle: {
    fontFamily: "'DM Sans', system-ui, sans-serif",
    fontSize: "1.1rem",
    fontWeight: 600,
    color: "#fff",
    marginBottom: "1rem",
  },
  detailGrid: {
    display: "flex",
    flexDirection: "column",
    gap: "1rem",
  },
  detailRow: {
    display: "flex",
    justifyContent: "space-between",
    alignItems: "center",
    padding: "0.75rem 0",
    borderBottom: "1px solid rgba(255, 255, 255, 0.05)",
  },
  detailLabel: {
    fontFamily: "'DM Sans', system-ui, sans-serif",
    fontSize: "0.9rem",
    color: "rgba(255, 255, 255, 0.6)",
  },
  detailValue: {
    fontFamily: "'DM Sans', system-ui, sans-serif",
    fontSize: "0.9rem",
    color: "#fff",
    fontWeight: 500,
  },
  actionSection: {
    marginTop: "2rem",
    paddingTop: "2rem",
    borderTop: "1px solid rgba(255, 255, 255, 0.1)",
  },
};
