"use client";

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

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)
};

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
 */
const getEditRoute = (fType: string, id: string, updateUrl?: string): string | null => {
  if (!id) return null;
  
  // If API provides updateUrl directly (like Yii's $data->stockUpdateUrl), use it
  if (updateUrl) {
    return updateUrl;
  }
  
  const normalizedType = fType?.toLowerCase().trim() || "";
  const encodedId = encodeURIComponent(id);
  
  // Map transaction types to their edit routes
  // Handle variations and case-insensitive matching
  if (normalizedType.includes("stock") && !normalizedType.includes("structure")) {
    return `/equity/stock/form?id=${encodedId}`;
  }
  
  if (normalizedType.includes("commodity") && !normalizedType.includes("derivative")) {
    return `/commodity/create?id=${encodedId}`;
  }
  
  if (normalizedType.includes("commodity") && normalizedType.includes("derivative")) {
    // Check if it's option or accumulator
    if (normalizedType.includes("option") || normalizedType.includes("commodity option")) {
      return `/commodity/derivative/option?id=${encodedId}`;
    } else if (normalizedType.includes("accumulator") || normalizedType.includes("commodity accumulator")) {
      return `/commodity/derivative/accumulator?id=${encodedId}`;
    }
    // Default derivative route
    return `/commodity/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")) {
    // Check if it's fixed deposit or call deposit
    if (normalizedType.includes("fixed") || normalizedType.includes("fixed deposit")) {
      return `/cash/deposit/fixeddeposit?id=${encodedId}`;
    } else if (normalizedType.includes("call") || normalizedType.includes("call deposit")) {
      return `/cash/deposit/calldeposit?id=${encodedId}`;
    }
    // Default deposit route
    return `/cash/deposit/create?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")) {
    return `/cash/interesttransaction/form?id=${encodedId}`;
  }
  
  if (normalizedType.includes("equity") && normalizedType.includes("derivative")) {
    // Check if it's option or accumulator
    if (normalizedType.includes("option") || normalizedType.includes("stock option")) {
      return `/equity/derivative/option?id=${encodedId}`;
    } else if (normalizedType.includes("accumulator") || normalizedType.includes("stock accumulator")) {
      return `/equity/derivative/accumulator?id=${encodedId}`;
    }
    // Default derivative route
    return `/equity/derivative/create?id=${encodedId}`;
  }
  
  // Default fallback to stock if type is unknown
  // This matches the original behavior
  return `/equity/stock/form?id=${encodedId}`;
};

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);
  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>
      <button type="button" onClick={handleEdit} className={commonClass} title="Edit">
        <PencilLine className="h-3.5 w-3.5" />
      </button>
    </div>
  );
};

export const createAllTransactionsColumns =
  (options: ActionHandlers = {}): ColumnDef<AllTransactions>[] => [
    {
      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",
      enableColumnFilter: true,
      filterFn: (row, id, value) => {
        const cellValue = String(row.getValue(id) || "").toLowerCase();
        return cellValue.includes(String(value || "").toLowerCase());
      },
    },
    {
      accessorKey: "bank_id",
      header: "Bank",
      enableColumnFilter: true,
      filterFn: (row, id, value) => {
        const cellValue = String(row.getValue(id) || "").toLowerCase();
        return cellValue.includes(String(value || "").toLowerCase());
      },
    },
    {
      accessorKey: "ticker",
      header: "Security Ticker",
      enableColumnFilter: true,
      cell: ({ row }) => {
        const value = row.original.ticker;
        return value && value.trim() !== "" ? value : "—";
      },
      filterFn: (row, id, value) => {
        const cellValue = String(row.original.ticker || "").toLowerCase();
        return cellValue.includes(String(value || "").toLowerCase());
      },
    },
    {
      accessorKey: "isin",
      header: "Name",
      enableColumnFilter: true,
      cell: ({ row }) => {
        const value = row.original.isin;
        return value && value.trim() !== "" ? value : "—";
      },
      filterFn: (row, id, value) => {
        const cellValue = 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;
        if (!amount || amount.trim() === "") return "—";
        
        const num = parseNumber(amount);
        const formatted = formatNumber(num);
        const colorClass = getAmountColor(num);
        
        return (
          <span className={colorClass}>
            {formatted}
          </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();
