"use client";

import { ColumnDef } from "@tanstack/react-table";
import { Eye, PencilLine, FileText } from "lucide-react";
import { useRouter } from "next/navigation";
import { parseNumber, formatNumber, getAmountColor } from "@/lib/common";
import { resolveFileUrl } from "@/components/datatable/liststock/columns";

export type AllTransactions = {
  id?: string;
  uid: string;
  t_date: string;
  bank_id: string;
  ticker: string | null;
  isin: string | null;
  f_type: string;
  price: string;
  quantity: string;
  purchase_currency_code: string;
  amount: string;
  updateUrl?: string; // Optional: if provided by API (similar to Yii's $data->stockUpdateUrl)
  f_type2?: string;  // Secondary type for deposits (fixed vs call)
  file_url?: string;
  file?: string;
  r_link?: string;
  document?: string;
  document_url?: string;
  file_path?: string;
  filePath?: string;
  commission?: string;
  chargesandfees?: string;
  federalturnovertax?: string;
  remark?: string;
  purpose?: string;
};

interface ActionHandlers {
  onView?: (record: AllTransactions) => void;
  onEdit?: (record: AllTransactions) => void;
}

/**
 * Maps transaction type (f_type) to the appropriate edit route
 * Similar to Yii's $data->stockUpdateUrl logic
 * If updateUrl is provided in the record, it takes precedence
 */
export const getEditRoute = (fType: string, id: string, updateUrl?: string, fType2?: string): string | null => {
  if (!id) return null;

  if (updateUrl?.startsWith("/")) {
    return updateUrl;
  }

  const normalizedType = fType?.toLowerCase().trim() || "";
  const normalizedType2 = fType2?.toLowerCase().trim() || "";
  const encodedId = encodeURIComponent(id);

  // ── Commodity derivatives (must come BEFORE generic option/accumulator checks) ──
  if (normalizedType.includes("commodity") && (
    normalizedType.includes("option") ||
    normalizedType.includes("accumulator") ||
    normalizedType.includes("derivative")
  )) {
    if (normalizedType.includes("option")) {
      return `/commodity/derivative/option?id=${encodedId}`;
    } else if (normalizedType.includes("accumulator")) {
      return `/commodity/derivative/accumulator?id=${encodedId}`;
    }
    return `/commodity/derivative/create?id=${encodedId}`;
  }

  // ── Plain commodity (no derivative) ──
  if (normalizedType.includes("commodity")) {
    return `/commodity/form?id=${encodedId}`;
  }

  // ── Equity derivatives ──
  if (normalizedType.includes("stock option") || normalizedType.includes("option")) {
    return `/equity/derivative/option?id=${encodedId}`;
  }

  if (normalizedType.includes("stock accumulator") || normalizedType.includes("accumulator")) {
    return `/equity/derivative/accumulator?id=${encodedId}`;
  }

  if (normalizedType.includes("equity") && normalizedType.includes("derivative")) {
    return `/equity/derivative/create?id=${encodedId}`;
  }

  if (normalizedType.includes("bond") && normalizedType.includes("fund")) {
    return `/fixedincome/bondfunds/form?id=${encodedId}`;
  }

  if (normalizedType.includes("bond") && !normalizedType.includes("fund")) {
    return `/fixedincome/bond/form?id=${encodedId}`;
  }

  if (normalizedType.includes("structure") || normalizedType.includes("structured")) {
    return `/equity/structure/form?id=${encodedId}`;
  }

  if (normalizedType.includes("other asset") || normalizedType.includes("alternative")) {
    return `/alternativeinvest/otherassets/form?id=${encodedId}`;
  }

  if (normalizedType.includes("deposit") || normalizedType2.includes("deposit")) {
    const depositSubType = normalizedType2 || normalizedType;
    if (depositSubType.includes("fixed")) {
      return `/cash/deposit/fixeddeposit?id=${encodedId}`;
    } else if (depositSubType.includes("call")) {
      return `/cash/deposit/calldeposit?id=${encodedId}`;
    }
    return `/cash/deposit/fixeddeposit?id=${encodedId}`;
  }

  if (normalizedType.includes("leverage")) {
    return `/cash/leverage/form?id=${encodedId}`;
  }

  if (normalizedType.includes("cash") && normalizedType.includes("derivative")) {
    return `/cash/derivative/create?id=${encodedId}`;
  }

  if (normalizedType.includes("currency") || normalizedType.includes("conversion")) {
    return `/cash/currencyconversion/create?id=${encodedId}`;
  }

  if (normalizedType.includes("cash") && (normalizedType.includes("withdraw") || normalizedType.includes("withdrawal"))) {
    return `/cash/cashwithdraw/form?id=${encodedId}`;
  }

  if (
    normalizedType.includes("interest") ||
    normalizedType.includes("dividend") ||
    normalizedType.includes("divident")
  ) {
    return `/cash/interesttransaction/form?id=${encodedId}`;
  }

  if (normalizedType.includes("stock") && !normalizedType.includes("structure")) {
    return `/equity/stock/form?id=${encodedId}`;
  }

  return `/equity/stock/form?id=${encodedId}`;
};

/**
 * Maps transaction type (f_type) to the appropriate delete API route.
 * This mirrors the routing strategy used by getEditRoute.
 */
export const getDeleteEndpoint = (fType: string, fType2?: string): string => {
  const normalizedType = fType?.toLowerCase().trim() || "";
  const normalizedType2 = fType2?.toLowerCase().trim() || "";

  if (
    normalizedType.includes("commodity") &&
    (
      normalizedType.includes("option") ||
      normalizedType.includes("accumulator") ||
      normalizedType.includes("derivative")
    )
  ) {
    return "/api/commodity/derivatives";
  }

  if (normalizedType.includes("commodity")) {
    return "/api/commodity";
  }

  if (normalizedType.includes("stock option") || normalizedType.includes("option")) {
    return "/api/equity/derivatives";
  }

  if (normalizedType.includes("stock accumulator") || normalizedType.includes("accumulator")) {
    return "/api/equity/derivatives";
  }

  if (normalizedType.includes("equity") && normalizedType.includes("derivative")) {
    return "/api/equity/derivatives";
  }

  if (normalizedType.includes("bond") && normalizedType.includes("fund")) {
    return "/api/fixedincome/bondfunds";
  }

  if (normalizedType.includes("bond") && !normalizedType.includes("fund")) {
    return "/api/fixedincome/bond";
  }

  if (normalizedType.includes("structure") || normalizedType.includes("structured")) {
    return "/api/equity/structure";
  }

  if (normalizedType.includes("other asset") || normalizedType.includes("alternative")) {
    return "/api/hedgefund";
  }

  if (normalizedType.includes("deposit") || normalizedType2.includes("deposit")) {
    const depositSubType = normalizedType2 || normalizedType;
    if (depositSubType.includes("fixed")) {
      return "/api/deposit/fixeddeposit/delete";
    }
    return "/api/deposit/calldeposit/delete";
  }

  if (normalizedType.includes("leverage")) {
    return "/api/leverage/delete";
  }

  if (normalizedType.includes("cash") && normalizedType.includes("derivative")) {
    return "/api/swaps/delete";
  }

  if (normalizedType.includes("currency") || normalizedType.includes("conversion")) {
    return "/api/currencyconversion/delete";
  }

  if (normalizedType.includes("cash") && (normalizedType.includes("withdraw") || normalizedType.includes("withdrawal"))) {
    return "/api/cashwithdrawal/delete";
  }

  if (
    normalizedType.includes("interest") ||
    normalizedType.includes("dividend") ||
    normalizedType.includes("divident")
  ) {
    return "/api/intrestdividend/delete";
  }

  if (normalizedType.includes("stock") && !normalizedType.includes("structure")) {
    return "/api/stock";
  }

  return "/api/stock";
};

const ActionsCell = ({
  record,
  onView,
  onEdit,
}: { record: AllTransactions } & ActionHandlers) => {
  const router = useRouter();
  const referencedId = record.id ?? record.uid;
  const viewHref = `/equity/stock/${referencedId}`;
  const editRoute = getEditRoute(record.f_type, referencedId, record.updateUrl, record.f_type2);
  const fileUrl = resolveFileUrl(record as Parameters<typeof resolveFileUrl>[0]);
  const commonClass =
    "inline-flex items-center gap-1 rounded-lg border border-[#428B4D]/30 bg-white px-2 py-1 text-xs font-medium text-slate-600 transition hover:-translate-y-0.5 hover:border-[#428B4D] hover:bg-[#428B4D] hover:text-white";

  const handleEdit = () => {
    if (!referencedId) {
      console.error("Missing transaction id for edit action", record);
      return;
    }
    if (onEdit) {
      onEdit(record);
      return;
    }
    if (editRoute) {
      router.push(editRoute);
    } else {
      console.error("Unable to determine edit route for transaction type:", record.f_type);
    }
  };

  return (
    <div className="flex items-center gap-2">
      <button
        type="button"
        onClick={() => {
          if (!referencedId) return;
          if (onView) {
            onView(record);
            return;
          }
          router.push(viewHref);
        }}
        className={commonClass}
        disabled={!referencedId}
        title="View"
      >
        <Eye className="h-3.5 w-3.5" />
      </button>
      {fileUrl && (
        <a
          href={fileUrl}
          target="_blank"
          rel="noopener noreferrer"
          className={commonClass}
          title="View Document"
        >
          <FileText className="h-3.5 w-3.5" />
          <span></span>
        </a>
      )}
      <button type="button" onClick={handleEdit} className={commonClass} title="Edit">
        <PencilLine className="h-3.5 w-3.5" />
      </button>
    </div>
  );
};

export const createAllTransactionsColumns = (
  options: ActionHandlers = {},
  data: AllTransactions[] = []
): ColumnDef<AllTransactions>[] => {
  
  const bankOptions = Array.from(
    new Set(data.map((d) => d.bank_id).filter(Boolean))
  ).map((name) => ({ label: name, value: name }));

  return [
    {
      accessorKey: "uid",
      header: "Ref ID",
      enableColumnFilter: true,
      filterFn: (row, id, value) => {
        // Exact match for refID - only show rows where refID equals the search value
        const cellValue = String(row.getValue(id) || "");
        const searchValue = String(value || "");
        if (!searchValue) return true;
        return cellValue === searchValue;
      },
    },
    {
      accessorKey: "t_date",
      header: "Placement Date",
      filterFn: "dateRange" as any,
      meta: { filterVariant: "dateRange" as const },
    },
    {
      accessorKey: "bank_id",
      header: "Bank",
      enableColumnFilter: true,
      filterFn: (row, id, value) => {
        if (!value || (Array.isArray(value) && value.length === 0)) return true;
        const cellValue = String(row.getValue(id)).trim();
        if (Array.isArray(value)) return value.map((v) => v.trim()).includes(cellValue);
        return cellValue === String(value).trim();
      },
      meta: {
        filterVariant: "select" as const,
        selectOptions: bankOptions, 
      },
    },
    {
  accessorKey: "ticker",
  header: "Security Ticker",
  enableColumnFilter: true,
  cell: ({ row }) => {
    console.log(row);
        const fType = row.original.f_type?.toLowerCase() || "";

    const value = (fType.includes("withdrawal") || fType.includes("widthdrawal"))
      ? row.original.remark
      : row.original.ticker;

    return value && value.trim() !== "" ? value : "—";
  },
    filterFn: (row, id, value) => {
        const fType = row.original.f_type?.toLowerCase() || "";

      const cellValue = (fType.includes("withdrawal") || fType.includes("widthdrawal"))
        ? String(row.original.remark || "").toLowerCase()
        : String(row.original.ticker || "").toLowerCase();

      return cellValue.includes(String(value || "").toLowerCase());
    },
  },
  {
    accessorKey: "isin",
    header: "Name",
    enableColumnFilter: true,
    cell: ({ row }) => {
      const fType = row.original.f_type?.toLowerCase() || "";

      const value = (fType.includes("withdrawal") || fType.includes("widthdrawal"))
        ? row.original.purpose
        : row.original.isin;

      return value && value.trim() !== "" ? value : "—";
    },
    filterFn: (row, id, value) => {
        const fType = row.original.f_type?.toLowerCase() || "";

      const cellValue = (fType.includes("withdrawal") || fType.includes("widthdrawal"))
        ? String(row.original.purpose || "").toLowerCase()
        : String(row.original.isin || "").toLowerCase();

      return cellValue.includes(String(value || "").toLowerCase());
    },
  },
    {
      accessorKey: "f_type",
      header: "Category",
      enableColumnFilter: true,
      filterFn: (row, id, value) => {
        const cellValue = String(row.getValue(id) || "").toLowerCase();
        return cellValue.includes(String(value || "").toLowerCase());
      },
    },
    {
      accessorKey: "price",
      header: "Price",
      enableColumnFilter: true,
      filterFn: (row, id, value) => {
        const cellValue = String(row.getValue(id) || "").toLowerCase();
        return cellValue.includes(String(value || "").toLowerCase());
      },
    },
    {
      accessorKey: "quantity",
      header: "Quantity",
      enableColumnFilter: true,
      filterFn: (row, id, value) => {
        const cellValue = String(row.getValue(id) || "").toLowerCase();
        return cellValue.includes(String(value || "").toLowerCase());
      },
    },
    {
      accessorKey: "purchase_currency_code",
      header: "Currency",
      enableColumnFilter: true,
      filterFn: (row, id, value) => {
        const cellValue = String(row.getValue(id) || "").toLowerCase();
        return cellValue.includes(String(value || "").toLowerCase());
      },
    },
    {
      accessorKey: "amount",
      header: "Amount",
      enableColumnFilter: true,
      cell: ({ row }) => {
        const amount = row.original.amount;
        const fType = row.original.f_type?.toLowerCase() || "";
        if (!amount || amount.trim() === "") return "—";

        const num = parseNumber(amount);
        const absFormatted = formatNumber(Math.abs(num));

        if (fType.includes("withdrawal") || fType.includes("widthdrawal")) {
          return <span className="text-red-600">-{absFormatted}</span>;
        } else if (fType.includes("deposit")) {
          return <span className="text-green-600">{absFormatted}</span>;
        }

        const colorClass = getAmountColor(num);
        return <span className={colorClass}>{formatNumber(num)}</span>;
      },
      filterFn: (row, id, value) => {
        const cellValue = String(row.original.amount || "").toLowerCase();
        return cellValue.includes(String(value || "").toLowerCase());
      },
    },
    {
      id: "actions",
      header: "Actions",
      enableColumnFilter: false,
      cell: ({ row }) => <ActionsCell record={row.original} {...options} />,
    },
  ];
}

export const columns: ColumnDef<AllTransactions>[] =
  createAllTransactionsColumns();
