"use client";

import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { PositionsTable } from "./PositionsTable";
import type { OcrExtractedData, OcrPosition, CashPosition } from "@/types/ocr";

interface ReviewPositionsDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  filename: string;
  extractedData: OcrExtractedData | undefined;
}

function normalizeCashPositions(cashPositions: CashPosition[]): OcrPosition[] {
  return cashPositions.map((cash) => {
    let cashName = (cash.Description || "").trim();
    const originalName = cashName;

    // Remove account numbers (patterns like "83.61738.0 4000")
    if (cashName && /^\d+\.\d+\.\d+\s+\d+$/.test(cashName)) {
      cashName = "";
    }

    // Determine Cash vs Leverage
    const cashAssetType = cash.AssetType || "";
    let isLeverage = false;

    if (cashAssetType && cashAssetType.toLowerCase() === "leverage") {
      isLeverage = true;
    } else if (originalName && !originalName.toLowerCase().startsWith("current")) {
      isLeverage = true;
    }

    if (isLeverage) {
      cashName = originalName || (cash.Currency ? `Loan ${cash.Currency}` : "Loan");
    } else {
      if (cashName && cashName.toLowerCase().indexOf("current") === -1) {
        cashName = `Current ${cashName}`;
      } else if (!cashName && cash.Currency) {
        cashName = `Current account ${cash.Currency}`;
      } else if (!cashName) {
        cashName = "Current account";
      }
    }

    return {
      Type: isLeverage ? "Leverage" : "Cash",
      AssetType: isLeverage ? "Leverage" : "Cash",
      Currency: cash.Currency || "",
      Quantity: cash.Nominal || "",
      Name: cashName,
      Country: "",
      PurchasePrice: cash.PurchasePrice || "",
      PurchasePriceFX: "",
      MarketPrice: "",
      MarketPriceFX: "",
      Value: cash.ValuationUSD || cash.Nominal || "",
      ISIN: "",
    };
  });
}

export function ReviewPositionsDialog({
  open,
  onOpenChange,
  filename,
  extractedData,
}: ReviewPositionsDialogProps) {
  const bondPositions = extractedData?.bondPositions || [];
  const equityPositions = extractedData?.equityPositions || [];
  const cashPositions = extractedData?.cashPositions || [];

  const allPositions: OcrPosition[] = [
    ...bondPositions.map((b) => ({ ...b, Type: "Bond" })),
    ...equityPositions.map((e) => ({ ...e, Type: "Equity" })),
    ...normalizeCashPositions(cashPositions),
  ];

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[95vw] max-w-[1600px] max-h-[90vh] overflow-hidden bg-white text-gray-900 p-0 rounded-2xl border-gray-200/80 shadow-2xl">
        {/* Header */}
        <DialogHeader className="px-6 pt-5 pb-3 border-b border-gray-100 bg-gradient-to-r from-white via-gray-50/50 to-white">
          <DialogTitle className="text-sm font-semibold text-gray-800 flex items-center gap-2.5">
            <span className="flex items-center justify-center w-7 h-7 rounded-lg bg-[#428B4D]/10">
              <svg className="w-4 h-4 text-[#428B4D]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
              </svg>
            </span>
            <span className="truncate">{filename}</span>
          </DialogTitle>
        </DialogHeader>

        {/* Scrollable Content */}
        <div className="overflow-y-auto max-h-[calc(90vh-80px)] px-5 pb-5">
          <PositionsTable
            positions={allPositions}
            bondCount={bondPositions.length}
            equityCount={equityPositions.length}
            cashCount={cashPositions.length}
          />
        </div>
      </DialogContent>
    </Dialog>
  );
}
