/**
 * Transaction Pipeline Component
 * Kanban-style pipeline board for real estate transactions with columns for each
 * TransactionStage, drag-friendly cards, pipeline value summary, and transaction editing
 */

"use client";

import { useState, useEffect, useCallback } from "react";
import type { Lang } from "@/lib/config";
import { fetchWithCSRF } from "@/lib/csrf-client";
import {
  Plus,
  Loader2,
  RefreshCw,
  User,
  Building2,
  DollarSign,
  Clock,
  ChevronDown,
  ChevronUp,
  X,
  Edit3,
  Phone,
  Mail,
} from "lucide-react";

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

interface Transaction {
  id: string;
  clientName: string;
  clientPhone?: string;
  clientEmail?: string;
  propertyId: string;
  propertyTitle: string;
  stage: string;
  offerAmount?: number;
  currency: string;
  daysInStage: number;
  notes?: string;
  createdAt: string;
  updatedAt: string;
}

interface TransactionPipelineProps {
  lang: Lang;
}

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

const STAGES = [
  {
    key: "INQUIRY",
    label: "Inquiry",
    color: "bg-slate-500",
    borderColor: "border-slate-300",
    bgColor: "bg-slate-50",
  },
  {
    key: "QUALIFIED",
    label: "Qualified",
    color: "bg-blue-500",
    borderColor: "border-blue-300",
    bgColor: "bg-blue-50",
  },
  {
    key: "VIEWING_SCHEDULED",
    label: "Viewing Scheduled",
    color: "bg-indigo-500",
    borderColor: "border-indigo-300",
    bgColor: "bg-indigo-50",
  },
  {
    key: "VIEWING_COMPLETED",
    label: "Viewing Done",
    color: "bg-violet-500",
    borderColor: "border-violet-300",
    bgColor: "bg-violet-50",
  },
  {
    key: "INTERESTED",
    label: "Interested",
    color: "bg-purple-500",
    borderColor: "border-purple-300",
    bgColor: "bg-purple-50",
  },
  {
    key: "OFFER_MADE",
    label: "Offer Made",
    color: "bg-amber-500",
    borderColor: "border-amber-300",
    bgColor: "bg-amber-50",
  },
  {
    key: "NEGOTIATION",
    label: "Negotiation",
    color: "bg-orange-500",
    borderColor: "border-orange-300",
    bgColor: "bg-orange-50",
  },
  {
    key: "OFFER_ACCEPTED",
    label: "Offer Accepted",
    color: "bg-lime-500",
    borderColor: "border-lime-300",
    bgColor: "bg-lime-50",
  },
  {
    key: "DEPOSIT_PAID",
    label: "Deposit Paid",
    color: "bg-teal-500",
    borderColor: "border-teal-300",
    bgColor: "bg-teal-50",
  },
  {
    key: "CONTRACT_SIGNED",
    label: "Contract Signed",
    color: "bg-cyan-500",
    borderColor: "border-cyan-300",
    bgColor: "bg-cyan-50",
  },
  {
    key: "PAYMENT_PROCESSING",
    label: "Payment Processing",
    color: "bg-sky-500",
    borderColor: "border-sky-300",
    bgColor: "bg-sky-50",
  },
  {
    key: "TX_COMPLETED",
    label: "Completed",
    color: "bg-emerald-500",
    borderColor: "border-emerald-300",
    bgColor: "bg-emerald-50",
  },
  {
    key: "LOST",
    label: "Lost",
    color: "bg-red-500",
    borderColor: "border-red-300",
    bgColor: "bg-red-50",
  },
];

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function showToast(
  type: "success" | "error" | "info" | "warning",
  title: string,
  message: string,
) {
  const event = new CustomEvent("showToast", {
    detail: { type, title, message },
  });
  window.dispatchEvent(event);
}

function formatCurrency(amount: number, currency: string) {
  return (
    new Intl.NumberFormat("en-US", {
      style: "decimal",
      maximumFractionDigits: 0,
    }).format(amount) + ` ${currency}`
  );
}

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

export default function TransactionPipeline({
  lang,
}: TransactionPipelineProps) {
  const isAr = lang === "ar";

  const [transactions, setTransactions] = useState<Transaction[]>([]);
  const [loading, setLoading] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);

  // New Transaction form
  const [showNewForm, setShowNewForm] = useState(false);
  const [newFormData, setNewFormData] = useState({
    clientName: "",
    clientPhone: "",
    clientEmail: "",
    propertyId: "",
    propertyTitle: "",
    stage: "INQUIRY",
    offerAmount: "",
    currency: "QAR",
    notes: "",
  });
  const [isSaving, setIsSaving] = useState(false);

  // Edit
  const [editingTransaction, setEditingTransaction] =
    useState<Transaction | null>(null);
  const [editStage, setEditStage] = useState("");

  // Collapsed columns
  const [collapsedCols, setCollapsedCols] = useState<Set<string>>(new Set());

  const fetchTransactions = useCallback(async () => {
    try {
      setLoading(true);
      const res = await fetch("/api/real-estate/transactions");
      const data = await res.json();
      if (data.success) {
        setTransactions(data.transactions || []);
      }
    } catch (error) {
      console.error("Failed to fetch transactions:", error);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchTransactions();
  }, [fetchTransactions]);

  const handleRefresh = async () => {
    setIsRefreshing(true);
    await fetchTransactions();
    setTimeout(() => setIsRefreshing(false), 500);
  };

  // Group by stage
  const byStage: Record<string, Transaction[]> = {};
  STAGES.forEach((s) => {
    byStage[s.key] = [];
  });
  transactions.forEach((t) => {
    if (byStage[t.stage]) {
      byStage[t.stage].push(t);
    } else {
      byStage["INQUIRY"].push(t);
    }
  });

  // Pipeline summary
  const totalValue = transactions
    .filter((t) => t.offerAmount && t.stage !== "LOST")
    .reduce((sum, t) => sum + (t.offerAmount || 0), 0);

  const activeCount = transactions.filter(
    (t) => t.stage !== "TX_COMPLETED" && t.stage !== "LOST",
  ).length;
  const completedCount = transactions.filter(
    (t) => t.stage === "TX_COMPLETED",
  ).length;
  const lostCount = transactions.filter((t) => t.stage === "LOST").length;

  const toggleColumn = (key: string) => {
    setCollapsedCols((prev) => {
      const next = new Set(prev);
      if (next.has(key)) {
        next.delete(key);
      } else {
        next.add(key);
      }
      return next;
    });
  };

  // Move transaction to a different stage
  const moveTransaction = async (txId: string, newStage: string) => {
    try {
      const res = await fetchWithCSRF(
        `/api/real-estate/transactions/${txId}/stage`,
        {
          method: "PATCH",
          body: JSON.stringify({ stage: newStage }),
        },
      );
      const data = await res.json();
      if (data.success) {
        setTransactions((prev) =>
          prev.map((t) =>
            t.id === txId ? { ...t, stage: newStage, daysInStage: 0 } : t,
          ),
        );
        showToast(
          "success",
          "Stage Updated",
          `Transaction moved to ${STAGES.find((s) => s.key === newStage)?.label || newStage}`,
        );
      } else {
        showToast("error", "Error", data.error || "Failed to move transaction");
      }
    } catch (error) {
      console.error("Failed to move transaction:", error);
      showToast("error", "Error", "An error occurred");
    }
  };

  // Save new transaction
  const handleCreateTransaction = async () => {
    if (!newFormData.clientName.trim()) return;

    setIsSaving(true);
    try {
      const body = {
        clientName: newFormData.clientName.trim(),
        clientPhone: newFormData.clientPhone.trim() || null,
        clientEmail: newFormData.clientEmail.trim() || null,
        propertyId: newFormData.propertyId || null,
        stage: newFormData.stage,
        offerAmount: newFormData.offerAmount
          ? parseFloat(newFormData.offerAmount)
          : null,
        currency: newFormData.currency,
        notes: newFormData.notes.trim() || null,
      };

      const res = await fetchWithCSRF("/api/real-estate/transactions", {
        method: "POST",
        body: JSON.stringify(body),
      });

      const data = await res.json();
      if (data.success) {
        showToast(
          "success",
          "Transaction Created",
          "New transaction added to pipeline",
        );
        setShowNewForm(false);
        setNewFormData({
          clientName: "",
          clientPhone: "",
          clientEmail: "",
          propertyId: "",
          propertyTitle: "",
          stage: "INQUIRY",
          offerAmount: "",
          currency: "QAR",
          notes: "",
        });
        fetchTransactions();
      } else {
        showToast(
          "error",
          "Error",
          data.error || "Failed to create transaction",
        );
      }
    } catch (error) {
      console.error("Failed to create transaction:", error);
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <div className="rounded-2xl bg-white border border-slate-200/80 shadow-sm overflow-hidden">
      {/* Header */}
      <div className="border-b border-slate-100 p-5">
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <div>
            <div className="flex items-center gap-3">
              <h2 className="text-lg font-bold text-slate-900">
                {isAr ? "خط أنابيب المعاملات" : "Transaction Pipeline"}
              </h2>
              <button
                onClick={handleRefresh}
                disabled={isRefreshing}
                className="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 bg-slate-50 px-2.5 py-1.5 text-xs font-medium text-slate-600 hover:bg-slate-100 transition-all disabled:opacity-50"
              >
                <RefreshCw
                  className={`w-3.5 h-3.5 ${isRefreshing ? "animate-spin" : ""}`}
                />
              </button>
            </div>
            <p className="text-sm text-slate-500 mt-0.5">
              {isAr
                ? "تتبع الصفقات من الاستفسار إلى الإغلاق"
                : "Track deals from inquiry to closing"}
            </p>
          </div>
          <button
            onClick={() => setShowNewForm(true)}
            className="inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-brand-green to-emerald-600 px-4 py-2.5 text-sm font-semibold text-white shadow-lg shadow-brand-green/25 hover:shadow-brand-green/40 hover:-translate-y-0.5 transition-all"
          >
            <Plus className="w-4 h-4" />
            {isAr ? "معاملة جديدة" : "New Transaction"}
          </button>
        </div>

        {/* Summary Stats */}
        <div className="mt-4 grid grid-cols-2 sm:grid-cols-4 gap-3">
          <div className="rounded-xl bg-gradient-to-br from-brand-green/10 to-emerald-50 border border-emerald-200/50 p-3">
            <p className="text-xs text-emerald-600 font-medium">
              {isAr ? "قيمة خط الأنابيب" : "Pipeline Value"}
            </p>
            <p className="text-lg font-bold text-emerald-700">
              {formatCurrency(totalValue, "QAR")}
            </p>
          </div>
          <div className="rounded-xl bg-blue-50 border border-blue-200/50 p-3">
            <p className="text-xs text-blue-600 font-medium">
              {isAr ? "صفقات نشطة" : "Active Deals"}
            </p>
            <p className="text-lg font-bold text-blue-700">{activeCount}</p>
          </div>
          <div className="rounded-xl bg-emerald-50 border border-emerald-200/50 p-3">
            <p className="text-xs text-emerald-600 font-medium">
              {isAr ? "مكتملة" : "Completed"}
            </p>
            <p className="text-lg font-bold text-emerald-700">
              {completedCount}
            </p>
          </div>
          <div className="rounded-xl bg-red-50 border border-red-200/50 p-3">
            <p className="text-xs text-red-600 font-medium">
              {isAr ? "خسائر" : "Lost"}
            </p>
            <p className="text-lg font-bold text-red-700">{lostCount}</p>
          </div>
        </div>
      </div>

      {/* Pipeline Content */}
      <div className="p-5">
        {loading ? (
          <div className="flex items-center justify-center py-16">
            <Loader2 className="w-8 h-8 text-brand-green animate-spin" />
          </div>
        ) : (
          <div className="flex gap-3 overflow-x-auto pb-4">
            {STAGES.map((stage) => {
              const items = byStage[stage.key] || [];
              const stageValue = items
                .filter((t) => t.offerAmount)
                .reduce((s, t) => s + (t.offerAmount || 0), 0);
              const isCollapsed = collapsedCols.has(stage.key);

              return (
                <div
                  key={stage.key}
                  className={`shrink-0 ${isCollapsed ? "w-12" : "w-64"} transition-all duration-200`}
                >
                  {/* Column Header */}
                  <div
                    className={`rounded-t-xl p-3 ${stage.bgColor} border ${stage.borderColor} border-b-0 cursor-pointer`}
                    onClick={() => toggleColumn(stage.key)}
                  >
                    {isCollapsed ? (
                      <div className="flex flex-col items-center gap-1">
                        <div
                          className={`w-2.5 h-2.5 rounded-full ${stage.color}`}
                        />
                        <span
                          className="text-[10px] font-bold text-slate-500 writing-mode-vertical"
                          style={{ writingMode: "vertical-lr" }}
                        >
                          {stage.label}
                        </span>
                        <span className="text-[10px] font-bold text-slate-700">
                          {items.length}
                        </span>
                      </div>
                    ) : (
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                          <span
                            className={`w-2.5 h-2.5 rounded-full ${stage.color}`}
                          />
                          <span className="text-xs font-bold text-slate-700">
                            {stage.label}
                          </span>
                          <span className="text-[10px] font-bold bg-white/80 rounded-full px-1.5 py-0.5 text-slate-600">
                            {items.length}
                          </span>
                        </div>
                        {isCollapsed ? (
                          <ChevronDown className="w-3.5 h-3.5 text-slate-400" />
                        ) : (
                          <ChevronUp className="w-3.5 h-3.5 text-slate-400" />
                        )}
                      </div>
                    )}
                    {!isCollapsed && stageValue > 0 && (
                      <p className="text-[10px] text-slate-500 mt-1">
                        {formatCurrency(stageValue, "QAR")}
                      </p>
                    )}
                  </div>

                  {/* Column Body */}
                  {!isCollapsed && (
                    <div
                      className={`rounded-b-xl border ${stage.borderColor} border-t-0 bg-white min-h-[200px] p-2 space-y-2`}
                    >
                      {items.length === 0 ? (
                        <p className="text-[10px] text-slate-300 text-center py-8">
                          {isAr ? "لا صفقات" : "No deals"}
                        </p>
                      ) : (
                        items.map((tx) => (
                          <div
                            key={tx.id}
                            className="rounded-lg border border-slate-200 bg-white p-3 shadow-sm hover:shadow-md hover:-translate-y-0.5 transition-all cursor-pointer"
                            onClick={() => {
                              setEditingTransaction(tx);
                              setEditStage(tx.stage);
                            }}
                          >
                            <div className="flex items-start justify-between gap-1">
                              <p className="text-xs font-bold text-slate-900 line-clamp-1">
                                {tx.clientName}
                              </p>
                              <span className="text-[10px] text-slate-400 shrink-0">
                                {tx.daysInStage}d
                              </span>
                            </div>
                            <p className="text-[10px] text-slate-500 mt-0.5 line-clamp-1 flex items-center gap-1">
                              <Building2 className="w-2.5 h-2.5 shrink-0" />
                              {tx.propertyTitle}
                            </p>
                            {tx.offerAmount != null && tx.offerAmount > 0 && (
                              <p className="text-xs font-bold text-brand-green mt-1">
                                {formatCurrency(tx.offerAmount, tx.currency)}
                              </p>
                            )}
                          </div>
                        ))
                      )}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* New Transaction Modal */}
      {showNewForm && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center p-4"
          onClick={() => setShowNewForm(false)}
        >
          <div className="absolute inset-0 bg-slate-900/80 backdrop-blur-sm" />
          <div
            className="relative w-full max-w-lg bg-white rounded-2xl shadow-2xl overflow-hidden"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="px-6 pt-6 pb-4 border-b border-slate-100">
              <div className="flex items-center justify-between">
                <h3 className="text-lg font-bold text-slate-900">
                  {isAr ? "معاملة جديدة" : "New Transaction"}
                </h3>
                <button
                  onClick={() => setShowNewForm(false)}
                  className="p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-lg transition-all"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>
            </div>
            <div className="px-6 py-5 space-y-4 max-h-[60vh] overflow-y-auto">
              <div>
                <label className="text-sm font-semibold text-slate-700 mb-1.5 block">
                  {isAr ? "اسم العميل" : "Client Name"}{" "}
                  <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  value={newFormData.clientName}
                  onChange={(e) =>
                    setNewFormData((p) => ({
                      ...p,
                      clientName: e.target.value,
                    }))
                  }
                  placeholder="Enter client name"
                  className="w-full h-11 px-4 rounded-xl border-2 border-slate-200 bg-slate-50/50 text-sm focus:border-brand-green focus:ring-4 focus:ring-brand-green/20 focus:outline-none transition-all"
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-sm font-semibold text-slate-700 mb-1.5 block">
                    {isAr ? "الهاتف" : "Phone"}
                  </label>
                  <input
                    type="tel"
                    value={newFormData.clientPhone}
                    onChange={(e) =>
                      setNewFormData((p) => ({
                        ...p,
                        clientPhone: e.target.value,
                      }))
                    }
                    placeholder="+974 XXXX XXXX"
                    className="w-full h-11 px-4 rounded-xl border-2 border-slate-200 bg-slate-50/50 text-sm focus:border-brand-green focus:ring-4 focus:ring-brand-green/20 focus:outline-none transition-all"
                    dir="ltr"
                  />
                </div>
                <div>
                  <label className="text-sm font-semibold text-slate-700 mb-1.5 block">
                    {isAr ? "البريد الإلكتروني" : "Email"}
                  </label>
                  <input
                    type="email"
                    value={newFormData.clientEmail}
                    onChange={(e) =>
                      setNewFormData((p) => ({
                        ...p,
                        clientEmail: e.target.value,
                      }))
                    }
                    className="w-full h-11 px-4 rounded-xl border-2 border-slate-200 bg-slate-50/50 text-sm focus:border-brand-green focus:ring-4 focus:ring-brand-green/20 focus:outline-none transition-all"
                    dir="ltr"
                  />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-sm font-semibold text-slate-700 mb-1.5 block">
                    {isAr ? "المرحلة الأولية" : "Initial Stage"}
                  </label>
                  <select
                    value={newFormData.stage}
                    onChange={(e) =>
                      setNewFormData((p) => ({ ...p, stage: e.target.value }))
                    }
                    className="w-full h-11 px-4 rounded-xl border-2 border-slate-200 bg-slate-50/50 text-sm appearance-none cursor-pointer focus:border-brand-green focus:ring-4 focus:ring-brand-green/20 focus:outline-none transition-all"
                  >
                    {STAGES.map((s) => (
                      <option key={s.key} value={s.key}>
                        {s.label}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="text-sm font-semibold text-slate-700 mb-1.5 block">
                    {isAr ? "مبلغ العرض" : "Offer Amount"}
                  </label>
                  <input
                    type="number"
                    value={newFormData.offerAmount}
                    onChange={(e) =>
                      setNewFormData((p) => ({
                        ...p,
                        offerAmount: e.target.value,
                      }))
                    }
                    placeholder="0"
                    min="0"
                    className="w-full h-11 px-4 rounded-xl border-2 border-slate-200 bg-slate-50/50 text-sm focus:border-brand-green focus:ring-4 focus:ring-brand-green/20 focus:outline-none transition-all"
                    dir="ltr"
                  />
                </div>
              </div>
              <div>
                <label className="text-sm font-semibold text-slate-700 mb-1.5 block">
                  {isAr ? "ملاحظات" : "Notes"}
                </label>
                <textarea
                  value={newFormData.notes}
                  onChange={(e) =>
                    setNewFormData((p) => ({ ...p, notes: e.target.value }))
                  }
                  rows={2}
                  className="w-full px-4 py-2.5 rounded-xl border-2 border-slate-200 bg-slate-50/50 text-sm focus:border-brand-green focus:ring-4 focus:ring-brand-green/20 focus:outline-none transition-all resize-none"
                />
              </div>
            </div>
            <div className="px-6 py-4 bg-slate-50 border-t border-slate-200 flex justify-end gap-3">
              <button
                onClick={() => setShowNewForm(false)}
                className="px-5 py-2.5 rounded-xl border-2 border-slate-200 bg-white text-sm font-bold text-slate-600 hover:bg-slate-50 transition-all"
              >
                {isAr ? "إلغاء" : "Cancel"}
              </button>
              <button
                onClick={handleCreateTransaction}
                disabled={isSaving || !newFormData.clientName.trim()}
                className="px-6 py-2.5 rounded-xl bg-gradient-to-r from-brand-green to-emerald-600 text-sm font-bold text-white shadow-lg shadow-brand-green/30 hover:shadow-brand-green/50 transition-all disabled:opacity-50 inline-flex items-center gap-2"
              >
                {isSaving && <Loader2 className="w-4 h-4 animate-spin" />}
                {isAr ? "إنشاء" : "Create"}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Edit Transaction Panel */}
      {editingTransaction && (
        <div
          className="fixed inset-0 z-50 flex justify-end"
          onClick={() => setEditingTransaction(null)}
        >
          <div className="absolute inset-0 bg-slate-900/50 backdrop-blur-sm" />
          <div
            className="relative w-full max-w-md bg-white shadow-2xl overflow-y-auto"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="sticky top-0 bg-white border-b border-slate-100 p-5 z-10">
              <div className="flex items-center justify-between">
                <h3 className="text-lg font-bold text-slate-900">
                  {isAr ? "تفاصيل المعاملة" : "Transaction Details"}
                </h3>
                <button
                  onClick={() => setEditingTransaction(null)}
                  className="p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-lg transition-all"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>
            </div>
            <div className="p-5 space-y-5">
              {/* Client */}
              <div>
                <h4 className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">
                  {isAr ? "العميل" : "Client"}
                </h4>
                <div className="space-y-1.5">
                  <div className="flex items-center gap-2 text-sm text-slate-700">
                    <User className="w-4 h-4 text-slate-400" />
                    <span className="font-medium">
                      {editingTransaction.clientName}
                    </span>
                  </div>
                  {editingTransaction.clientPhone && (
                    <div className="flex items-center gap-2 text-sm text-slate-700">
                      <Phone className="w-4 h-4 text-slate-400" />
                      <span>{editingTransaction.clientPhone}</span>
                    </div>
                  )}
                  {editingTransaction.clientEmail && (
                    <div className="flex items-center gap-2 text-sm text-slate-700">
                      <Mail className="w-4 h-4 text-slate-400" />
                      <span>{editingTransaction.clientEmail}</span>
                    </div>
                  )}
                </div>
              </div>

              {/* Property */}
              <div className="flex items-start gap-3 p-3 rounded-xl bg-slate-50 border border-slate-200">
                <Building2 className="w-5 h-5 text-brand-green mt-0.5 shrink-0" />
                <p className="text-sm font-medium text-slate-800">
                  {editingTransaction.propertyTitle}
                </p>
              </div>

              {/* Value */}
              {editingTransaction.offerAmount != null &&
                editingTransaction.offerAmount > 0 && (
                  <div className="flex items-center gap-3 p-3 rounded-xl bg-emerald-50 border border-emerald-200">
                    <DollarSign className="w-5 h-5 text-emerald-600 shrink-0" />
                    <p className="text-lg font-bold text-emerald-700">
                      {formatCurrency(
                        editingTransaction.offerAmount,
                        editingTransaction.currency,
                      )}
                    </p>
                  </div>
                )}

              {/* Time in Stage */}
              <div className="flex items-center gap-2 text-sm text-slate-500">
                <Clock className="w-4 h-4" />
                <span>
                  {editingTransaction.daysInStage}{" "}
                  {isAr ? "يوم في المرحلة الحالية" : "days in current stage"}
                </span>
              </div>

              {/* Notes */}
              {editingTransaction.notes && (
                <div>
                  <h4 className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">
                    {isAr ? "ملاحظات" : "Notes"}
                  </h4>
                  <p className="text-sm text-slate-600 whitespace-pre-wrap">
                    {editingTransaction.notes}
                  </p>
                </div>
              )}

              {/* Move Stage */}
              <div>
                <h4 className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-3">
                  {isAr ? "نقل إلى مرحلة" : "Move to Stage"}
                </h4>
                <select
                  value={editStage}
                  onChange={(e) => setEditStage(e.target.value)}
                  className="w-full h-11 px-4 rounded-xl border-2 border-slate-200 bg-slate-50/50 text-sm appearance-none cursor-pointer focus:border-brand-green focus:ring-4 focus:ring-brand-green/20 focus:outline-none transition-all mb-3"
                >
                  {STAGES.map((s) => (
                    <option key={s.key} value={s.key}>
                      {s.label}
                    </option>
                  ))}
                </select>
                <button
                  onClick={() => {
                    if (editStage !== editingTransaction.stage) {
                      moveTransaction(editingTransaction.id, editStage);
                      setEditingTransaction(null);
                    }
                  }}
                  disabled={editStage === editingTransaction.stage}
                  className="w-full px-4 py-2.5 rounded-xl bg-gradient-to-r from-brand-green to-emerald-600 text-sm font-bold text-white shadow-lg shadow-brand-green/30 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isAr ? "نقل المعاملة" : "Move Transaction"}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
