"use client";

import React, { useEffect, useState } from "react";
import { cn } from "@/lib/utils";
import SearchableSelect from "@/components/ui/SearchableSelect";
import { PRIMARY_COLOR, type CSSPropertiesWithVars } from "@/lib/common";

interface Currency {
  value: string;
  label: string;
}

interface OptionRowProps {
  currencies: Currency[]; // kept for compatibility
  rowData: {
    ticker: string;
    isin: string;
    reference_link: string;
    currency: string;
    spot_price: string;
    strike_price: string;
    quantity: string;
  };
  onChange: (updates: Partial<OptionRowProps["rowData"]>) => void;
  onAdd: () => void;
  onRemove: () => void;
  canRemove: boolean;
  showAddButton?: boolean;
  isReadOnly?: boolean;
}

export default function OptionRow({ currencies, rowData, onChange, onAdd, onRemove, canRemove, showAddButton = true, isReadOnly = false }: OptionRowProps) {
  const [selectedCurrency, setSelectedCurrency] = useState<{ label: string; value: string | number } | null>(
    rowData.currency ? { value: rowData.currency, label: rowData.currency } : null
  );

  useEffect(() => {
    if (!rowData.currency) {
      setSelectedCurrency(null);
      return;
    }

    const normalizedValue = String(rowData.currency);
    const matched = currencies.find((item) => String(item.value) === normalizedValue);

    setSelectedCurrency(
      matched
        ? { value: String(matched.value), label: matched.label }
        : { value: normalizedValue, label: normalizedValue }
    );
  }, [rowData.currency, currencies]);

  const handleAdd = (event: React.MouseEvent<HTMLButtonElement>) => {
    event.preventDefault();
    onAdd();
  };

  const handleRemove = (event: React.MouseEvent<HTMLButtonElement>) => {
    event.preventDefault();
    if (!canRemove) return;
    onRemove();
  };

  const handleCurrencyChange = (value: { label: string; value: string | number } | null) => {
    setSelectedCurrency(value);
    onChange({ currency: String(value?.value || "") });
  };

  return (
    <div className="rounded-lg bg-white p-4">
      {/* Hidden Fields */}
      <input
        type="hidden"
        name="options[underlying][]"
        defaultValue=""
      />
      <input
        type="hidden"
        name="options[sub_title][]"
        defaultValue=""
      />

      <div className="flex flex-wrap items-start gap-4">
        <div className="flex flex-1 min-w-[200px] max-w-[220px] flex-col gap-1.5">
          <label className="text-xs font-semibold uppercase tracking-wide text-slate-500">
            Security Ticker / ISIN
          </label>
          <input
            type="text"
              className="w-full rounded-lg border border-slate-200/80 bg-white px-3 py-2 text-sm text-slate-700 shadow-sm transition focus:outline-none focus:ring-2 focus:ring-opacity-30"
              style={{
                "--focus-border": PRIMARY_COLOR,
                "--focus-ring": `${PRIMARY_COLOR}4D`,
              } as CSSPropertiesWithVars}
              onFocus={(e) => {
                e.currentTarget.style.borderColor = PRIMARY_COLOR;
                e.currentTarget.style.boxShadow = `0 0 0 2px ${PRIMARY_COLOR}4D`;
              }}
              onBlur={(e) => {
                e.currentTarget.style.borderColor = "";
                e.currentTarget.style.boxShadow = "";
              }}
              name="options[ticker][]"
              required
              placeholder="e.g. AAPL"
            value={rowData.ticker}
            onChange={(e) => onChange({ ticker: e.target.value })}
            disabled={isReadOnly}
          />
        </div>

        <div className="flex flex-1 min-w-[200px] max-w-[240px] flex-col gap-1.5">
          <label className="text-xs font-semibold uppercase tracking-wide text-slate-500">
            Security Name
          </label>
          <input
            type="text"
              className="w-full rounded-lg border border-slate-200/80 bg-white px-3 py-2 text-sm text-slate-700 shadow-sm transition focus:outline-none focus:ring-2 focus:ring-opacity-30"
              style={{
                "--focus-border": PRIMARY_COLOR,
                "--focus-ring": `${PRIMARY_COLOR}4D`,
              } as CSSPropertiesWithVars}
              onFocus={(e) => {
                e.currentTarget.style.borderColor = PRIMARY_COLOR;
                e.currentTarget.style.boxShadow = `0 0 0 2px ${PRIMARY_COLOR}4D`;
              }}
              onBlur={(e) => {
                e.currentTarget.style.borderColor = "";
                e.currentTarget.style.boxShadow = "";
              }}
              name="options[isin][]"
              required
              placeholder="Full instrument name"
            value={rowData.isin}
            onChange={(e) => onChange({ isin: e.target.value })}
            disabled={isReadOnly}
          />
        </div>

        <div className="flex flex-1 min-w-[200px] max-w-[240px] flex-col gap-1.5">
          <label className="text-xs font-semibold uppercase tracking-wide text-slate-500">
            Reference Link
          </label>
          <input
            type="text"
              className="w-full rounded-lg border border-slate-200/80 bg-white px-3 py-2 text-sm text-slate-700 shadow-sm transition focus:outline-none focus:ring-2 focus:ring-opacity-30"
              style={{
                "--focus-border": PRIMARY_COLOR,
                "--focus-ring": `${PRIMARY_COLOR}4D`,
              } as CSSPropertiesWithVars}
              onFocus={(e) => {
                e.currentTarget.style.borderColor = PRIMARY_COLOR;
                e.currentTarget.style.boxShadow = `0 0 0 2px ${PRIMARY_COLOR}4D`;
              }}
              onBlur={(e) => {
                e.currentTarget.style.borderColor = "";
                e.currentTarget.style.boxShadow = "";
              }}
              name="options[reference_link][]"
              value={rowData.reference_link}
              onChange={(e) => onChange({ reference_link: e.target.value })}
            placeholder="Document / info URL"
            disabled={isReadOnly}
          />
        </div>

        <div className="flex flex-1 min-w-[140px] max-w-[160px] flex-col gap-1.5">
          {/* Hidden input for form submission */}
          <input
            type="hidden"
            name="options[currency][]"
            value={rowData.currency || selectedCurrency?.value || ""}
          />
          <SearchableSelect
            label="Currency"
            apiUrl="/api/searchabledropdown/currencylist"
            value={selectedCurrency}
            onChange={handleCurrencyChange}
            placeholder="Select currency"
            className="text-sm"
            isDisabled={isReadOnly}
          />
        </div>

        <div className="flex min-w-[110px] max-w-[130px] flex-col gap-1.5">
          <label className="text-xs font-semibold uppercase tracking-wide text-slate-500">
            Spot Price
          </label>
          <input
            type="text"
            name="options[spot_price][]"
            className="w-full rounded-lg border border-slate-200/80 bg-white px-3 py-2 text-sm text-slate-700 shadow-sm transition focus:outline-none focus:ring-2 focus:ring-opacity-30"
            required
            onInput={(e) => {
              const target = e.target as HTMLInputElement;
              target.value = target.value
                .replace(/[^0-9.]/g, "")
                .replace(/(\..*)\./g, "$1");
              onChange({ spot_price: target.value });
            }}
            value={rowData.spot_price}
            placeholder="0.00"
            disabled={isReadOnly}
          />
        </div>

        <div className="flex min-w-[110px] max-w-[130px] flex-col gap-1.5">
          <label className="text-xs font-semibold uppercase tracking-wide text-slate-500">
            Strike Price
          </label>
          <input
            type="text"
            name="options[strike_price][]"
            className="w-full rounded-lg border border-slate-200/80 bg-white px-3 py-2 text-sm text-slate-700 shadow-sm transition focus:outline-none focus:ring-2 focus:ring-opacity-30"
            required
            onInput={(e) => {
              const target = e.target as HTMLInputElement;
              target.value = target.value
                .replace(/[^0-9.]/g, "")
                .replace(/(\..*)\./g, "$1");
              onChange({ strike_price: target.value });
            }}
            value={rowData.strike_price}
            placeholder="0.00"
            disabled={isReadOnly}
          />
        </div>

        <div className="flex min-w-[110px] max-w-[130px] flex-col gap-1.5">
          <label className="text-xs font-semibold uppercase tracking-wide text-slate-500">
            Quantity
          </label>
          <input
            type="text"
            name="options[quantity][]"
            className="w-full rounded-lg border border-slate-200/80 bg-white px-3 py-2 text-sm text-slate-700 shadow-sm transition focus:outline-none focus:ring-2 focus:ring-opacity-30"
            required
            onInput={(e) => {
              const target = e.target as HTMLInputElement;
              target.value = target.value
                .replace(/[^0-9.]/g, "")
                .replace(/(\..*)\./g, "$1");
              onChange({ quantity: target.value });
            }}
            value={rowData.quantity}
            placeholder="0"
            disabled={isReadOnly}
          />
        </div>
        <div className="ml-auto flex self-end items-center gap-2 pb-0.5">
          {showAddButton && !isReadOnly ? (
            <button
              type="button"
              onClick={handleAdd}
              className="inline-flex items-center gap-1.5 rounded-lg border px-3 py-1.5 text-xs font-semibold transition hover:-translate-y-0.5 focus:outline-none focus-visible:ring-2 focus-visible:ring-opacity-40"
              style={{
                borderColor: `${PRIMARY_COLOR}66`,
                backgroundColor: `${PRIMARY_COLOR}1A`,
                color: PRIMARY_COLOR,
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.backgroundColor = PRIMARY_COLOR;
                e.currentTarget.style.color = "white";
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.backgroundColor = `${PRIMARY_COLOR}1A`;
                e.currentTarget.style.color = PRIMARY_COLOR;
              }}
              onFocus={(e) => {
                e.currentTarget.style.boxShadow = `0 0 0 2px ${PRIMARY_COLOR}66`;
              }}
              onBlur={(e) => {
                e.currentTarget.style.boxShadow = "";
              }}
            >
              <span className="text-base leading-none">＋</span>
              Add Row
            </button>
          ) : null}
          {!isReadOnly ? (
            <button
              type="button"
              onClick={handleRemove}
              disabled={!canRemove}
              className={cn(
                "inline-flex items-center gap-1.5 rounded-lg border px-3 py-1.5 text-xs font-semibold transition focus:outline-none focus-visible:ring-2",
                canRemove
                  ? "border-red-300/60 bg-red-50 text-red-500 hover:-translate-y-0.5 hover:bg-red-100 hover:text-red-600 focus-visible:ring-red-200"
                  : "cursor-not-allowed border-slate-200 bg-slate-100 text-slate-400"
              )}
            >
              <span className="text-base leading-none">✕</span>
              Remove
            </button>
          ) : null}
        </div>
      </div>

    </div>
  );
}
