"use client";

import { useEffect, useState, use } from "react";
import { useRouter } from "next/navigation";
import { PageHeader } from "@/components/ui/PageHeader";
import { BREADCRUMBS } from "@/constants/breadcrumbs";
import { apiGet } from "@/utils/api-client";
import { PositionsTable } from "@/components/ocr/PositionsTable";
import { StructureProductData } from "@/components/ocr/StructureProductData";
import type { OcrDocumentDetail, OcrPosition, CashPosition } from "@/types/ocr";
import { ArrowLeft, Loader2 } from "lucide-react";

function normalizeCashToPositions(cashPositions: CashPosition[]): OcrPosition[] {
  return cashPositions.map((cash) => {
    let name = (cash.Description || "").trim();
    const isLeverage =
      (cash.AssetType || "").toLowerCase() === "leverage" ||
      (name && !name.toLowerCase().startsWith("current"));

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

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

export default function OcrDocumentViewPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = use(params);
  const router = useRouter();
  const [data, setData] = useState<OcrDocumentDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function fetchDocument() {
      setLoading(true);
      try {
        const response = await apiGet<OcrDocumentDetail>(
          `/api/ocr/documents/${id}`
        );
        setData(response);
      } catch (err) {
        setError(
          err instanceof Error ? err.message : "Failed to load document"
        );
      } finally {
        setLoading(false);
      }
    }
    fetchDocument();
  }, [id]);

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

  const actions = (
    <button
      onClick={() => router.push("/ocr")}
      className="inline-flex items-center gap-1.5 px-3 py-2 text-xs font-medium border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50 transition-colors"
    >
      <ArrowLeft className="h-3.5 w-3.5" />
      Back to Documents
    </button>
  );

  if (loading) {
    return (
      <div className="container mx-auto px-4 py-10">
        <PageHeader
          title="OCR Document"
          breadcrumbs={[...BREADCRUMBS.ocrDocumentView]}
          actions={actions}
        />
        <div className="mt-6 flex items-center justify-center py-20">
          <Loader2 className="h-6 w-6 animate-spin text-gray-400" />
        </div>
      </div>
    );
  }

  if (error || !data) {
    return (
      <div className="container mx-auto px-4 py-10">
        <PageHeader
          title="OCR Document"
          breadcrumbs={[...BREADCRUMBS.ocrDocumentView]}
          actions={actions}
        />
        <div className="mt-6">
          <div className="bg-red-50 text-red-700 px-4 py-3 rounded text-sm">
            {error || "Document not found."}
          </div>
        </div>
      </div>
    );
  }

  const model = data.model;
  const clientInfo = data.clientInfo;

  return (
    <div className="container mx-auto px-4 py-10">
      <PageHeader
        title={`OCR Document - ${model.filename}`}
        breadcrumbs={[...BREADCRUMBS.ocrDocumentView]}
        actions={actions}
      />

      <div className="mt-6 space-y-6">
        {/* Document Information */}
        <div className="bg-white rounded-lg shadow-sm border p-5">
          <h3 className="text-sm font-semibold text-gray-700 mb-3">
            Document Information
          </h3>
          <table className="w-full text-xs">
            <tbody>
              {[
                ["Filename", model.filename],
                ["Bank Type", model.bank_type || "-"],
                ["Document Type", model.document_type || "-"],
                ["Extraction Date", model.extraction_date || "-"],
                ["Created At", model.created_at || "-"],
              ].map(([label, value]) => (
                <tr key={label} className="border-b last:border-0">
                  <td className="py-2 pr-4 font-medium text-gray-600 w-1/4">
                    {label}
                  </td>
                  <td className="py-2 text-gray-800">{value}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Client Information */}
        {clientInfo && (
          <div className="bg-white rounded-lg shadow-sm border p-5">
            <h3 className="text-sm font-semibold text-gray-700 mb-3">
              Client Information
            </h3>
            <table className="w-full text-xs">
              <tbody>
                {[
                  ["Client Name", clientInfo.clientName],
                  ["Client Number", clientInfo.clientNumber],
                  ["Portfolio Number", clientInfo.portfolioNumber],
                  ["Reference Currency", clientInfo.referenceCurrency],
                  ["Reference Date", clientInfo.referenceDate],
                  ["Creation Date", clientInfo.creationDate],
                ].map(
                  ([label, value]) =>
                    value && (
                      <tr key={label} className="border-b last:border-0">
                        <td className="py-2 pr-4 font-medium text-gray-600 w-1/4">
                          {label}
                        </td>
                        <td className="py-2 text-gray-800">{value}</td>
                      </tr>
                    )
                )}
              </tbody>
            </table>
          </div>
        )}

        {/* Bond & Equity Positions */}
        {allPositions.length > 0 && (
          <div className="bg-white rounded-lg shadow-sm border p-5">
            <h3 className="text-sm font-semibold text-gray-700 mb-3">
              Positions ({allPositions.length})
            </h3>
            <PositionsTable
              positions={allPositions}
              bondCount={(data.bondPositions || []).length}
              equityCount={(data.equityPositions || []).length}
              cashCount={(data.cashPositions || []).length}
            />
          </div>
        )}

        {/* Structure Product Data */}
        {(data.parentData || data.childData) && (
          <div className="bg-white rounded-lg shadow-sm border p-5">
            <h3 className="text-sm font-semibold text-gray-700 mb-3">
              Structure Product Data
            </h3>
            <StructureProductData
              parentData={data.parentData}
              childData={data.childData}
            />
          </div>
        )}
      </div>
    </div>
  );
}
