import { FileUploader } from "@/components/ui/FileUploader";
import SearchableSelect from "@/components/ui/SearchableSelect";
import { TextArea } from "@/components/ui/TextArea";
import { TextBox } from "@/components/ui/TextBox";
import OptionRow from "@/components/ui/OptionRow";
import DatePicker from "@/components/ui/DatePicker";
import PlacementDatePicker from "@/fields/PlacementDate";
import { Plus } from "lucide-react";
import { StructureFormField, UnderlyingOptionRowData } from "@/hooks/useEquityStructureForm";
import { formatDateToString } from "@/lib/common";
import { resolveFileUrl } from "@/components/datatable/liststock/columns";
import { useState,useRef,useEffect } from "react";
import SearchableSelect2 from "@/components/ui/SearchableSelect2"; // adjust path
type SecurityOption = {
  label: string;
  value: string;
  ticker?: string;
  isin?: string;
};
interface EquityStructureFormFieldsProps {
  formData: {
    p_currency: { label: string; value: string } | null;
    durationUnit: { label: string; value: string } | null;
    bank: { label: string; value: string } | null;
    existingFileUrl: string;
    bankadviserefno: string;
    placementdate: string;
    couponpercentage: string;
    expirydate: string;
    observationdate: string;
    kobarrier: string;
    producttype: string;
    structureamount: string;
    nocallperiod: string;
    strikepercentage: string;
    startdate: string;
    ticker: string;
    securityname: string;
    effectivedate: string;
    amount: string;
    commission: string;
    chargesandfees: string;
    federalturnovertax: string;
    relationshipmanager: string;
    description: string;
    remarks: string;
  };
  amountDisplayValue: string;
  isSaleFlow?: boolean;
  sourceUid?: string;
  rows: number[];
  underlyingOptions: UnderlyingOptionRowData[];
  currencies: { value: string; label: string }[];
  errors: Record<string, string>;
  clearError: (field: string) => void;
  handleFieldBlur: (field: StructureFormField, validateField: (field: StructureFormField) => string | undefined) => void;
  validateField: (field: StructureFormField) => string | undefined;
  updateFormData: (updates: any) => void;
  formatDateToString: (date: Date) => string;
  setShowBankModal: (show: boolean) => void;
  setErrors: (errors: Record<string, string> | ((prev: Record<string, string>) => Record<string, string>)) => void;
  addUnderlyingRow: () => void;
  removeUnderlyingRow: (index: number) => void;
  updateUnderlyingOption: (index: number, updates: Partial<UnderlyingOptionRowData>) => void;
  setSelectedFile: (file: File | null) => void;
}

export const EquityStructureFormFields = ({
  formData,
  amountDisplayValue,
  isSaleFlow,
  sourceUid,
  rows,
  underlyingOptions,
  currencies,
  errors,
  clearError,
  handleFieldBlur,
  validateField,
  updateFormData,
  formatDateToString,
  setShowBankModal,
  setErrors,
  addUnderlyingRow,
  removeUnderlyingRow,
  updateUnderlyingOption,
  setSelectedFile,
}: EquityStructureFormFieldsProps) => {
  const existingFileHref = formData.existingFileUrl
    ? resolveFileUrl({ r_link: formData.existingFileUrl })
    : "";
  const [selectedSecurity, setSelectedSecurity] = useState<SecurityOption | null>(null);
  const rawInputRef = useRef("");  // use ref instead of state (no timing issues)
  useEffect(() => {
    if (formData.ticker && !selectedSecurity) {
      setSelectedSecurity({
        label: `${formData.ticker} (${formData.securityname})`,
        value: formData.ticker,
        ticker: formData.ticker,
        isin: formData.securityname,
      });
    }
  }, [formData.ticker, formData.securityname]);
  return (
    <div className="grid grid-cols-1 sm:grid-cols-4 gap-6">
      {isSaleFlow ? (
        <TextBox
          label="Ref ID"
          value={sourceUid || ""}
          disabled
          placeholder=""
          className="text-sm"
        />
      ) : null}
      {/* Placement Date */}
      <PlacementDatePicker<StructureFormField>
        placementdate={formData.placementdate}
        setplacementdate={(placementdate) => updateFormData({ placementdate })}
        clearError={(field: string) => clearError(field as StructureFormField)}
        errors={errors}
        handleFieldBlur={handleFieldBlur}
        validateField={validateField}
        formatDateToString={formatDateToString}
      />

      {/* Coupon % */}
      <div className="group">
        <TextBox
          label="Coupon %"
          type="text"
          placeholder="Enter coupon percentage"
          className="text-sm transition-all duration-200 group-hover:shadow-md"
          value={formData.couponpercentage}
          onChange={(e) => updateFormData({ couponpercentage: e.target.value })}
          disabled={isSaleFlow}
        />
      </div>

      {/* Expiry Date */}
      <div className="group">
        <DatePicker
          label="Expiry Date"
          value={formData.expirydate}
          onChange={(date: Date) => updateFormData({ expirydate: formatDateToString(date) })}
          className="text-sm transition-all duration-200 group-hover:shadow-md"
          disabled={isSaleFlow}
        />
      </div>

      {/* Observation Date */}
      <div className="group">
        <DatePicker
          label="Observation Date"
          value={formData.observationdate}
          onChange={(date: Date) => updateFormData({ observationdate: formatDateToString(date) })}
          className="text-sm transition-all duration-200 group-hover:shadow-md"
          disabled={isSaleFlow}
        />
      </div>

      {/* KO Barrier */}
      <div className="group">
        <TextBox
          label="KO Barrier"
          type="text"
          placeholder="Enter KO barrier"
          className="text-sm transition-all duration-200 group-hover:shadow-md"
          value={formData.kobarrier}
          onChange={(e) => updateFormData({ kobarrier: e.target.value })}
          disabled={isSaleFlow}
        />
      </div>

      {/* Product Type */}
      <div className="group">
        <TextBox
          label="Product Type"
          type="text"
          placeholder="Enter product type"
          className="text-sm transition-all duration-200 group-hover:shadow-md"
          value={formData.producttype}
          onChange={(e) => updateFormData({ producttype: e.target.value })}
          disabled={isSaleFlow}
        />
      </div>
      
      {/* Security Ticker/ISIN */}
      <div className="group">
        <SearchableSelect2
          label="Security Ticker/ISIN"
          apiUrl="/api/searchabledropdown/autocomplete_stockname_by_name"
          value={selectedSecurity}
          displayValue={(option) => option?.ticker ?? option?.label?.split(" (")[0] ?? ""} 
          onInputChange={(inputValue) => {
            rawInputRef.current = inputValue;
          }}
          onChange={(option) => {
            const ticker       = option?.ticker ?? "";
            const securityname = option?.isin   ?? "";

            setSelectedSecurity(option as SecurityOption | null);
            updateFormData({ ticker, securityname });
            rawInputRef.current = "";
            clearError("ticker");
            clearError("isin");
            clearError("securityname");
          }}
          onBlur={() => {
            handleFieldBlur("ticker", validateField);
          }}
          placeholder="Type ticker or ISIN..."
          serverSideSearch={true}
          error={errors.ticker ?? errors.isin}
          isDisabled={isSaleFlow}
        />
    </div>

      {/* Structure Name */}
      <div className="group">
        <TextBox
          label="Structure Name"
          placeholder="Enter structure name"
          className="text-sm transition-all duration-200 group-hover:shadow-md"
          value={formData.securityname}
          onChange={(e) => {
            updateFormData({ securityname: e.target.value });
            clearError("securityname");
          }}
          onBlur={() => {
            if (!formData.securityname.trim()) {
              setErrors((prev) => ({ ...prev, securityname: "Structure name is required." }));
            }
          }}
          error={errors.securityname}
          disabled={isSaleFlow}
        />
      </div>
      
      {/* Structure Amount */}
      <div className="group">
        <TextBox
          label="Structure Amount"
          placeholder="Enter structure amount"
          className="text-sm transition-all duration-200 group-hover:shadow-md"
          value={formData.structureamount}
          onChange={(e) => updateFormData({ structureamount: e.target.value })}
          disabled={isSaleFlow}
        />
      </div>

      {/* Non Call Period + Duration Unit */}
      <div className="group sm:col-span-2">
        <div className="flex gap-4 items-end">
          <div className="flex-1">
            <TextBox
              label="Non Call Period"
              placeholder="Enter non call period"
              className="text-sm transition-all duration-200 group-hover:shadow-md"
              value={formData.nocallperiod}
              onChange={(e) => updateFormData({ nocallperiod: e.target.value })}
              disabled={isSaleFlow}
            />
          </div>
          <div className="flex-1">
            <SearchableSelect
              label=" "
              apiUrl="/api/searchabledropdown/daysduration"
              value={formData.durationUnit}
              onChange={(durationUnit) => updateFormData({ durationUnit })}
              placeholder="Select unit..."
              isDisabled={isSaleFlow}
            />
          </div>
        </div>
      </div>

      {/* Amount (Disabled) */}
      <div className="group">
        <div className="relative">
          <TextBox
            label="Amount"
            placeholder="Auto-calculated"
            type="number"
            className="text-sm bg-gradient-to-r from-slate-50 to-slate-100/50 border-slate-300/50 font-semibold text-slate-700"
            value={amountDisplayValue}
            onChange={(e) => updateFormData({ amount: e.target.value })}
            disabled
            readOnly
          />
          <div className="absolute inset-0 pointer-events-none rounded-lg bg-gradient-to-br from-[#428B4D]/5 to-transparent"></div>
        </div>
      </div>

      {/* Currency */}
      <div className="group">
        <SearchableSelect
          label="Currency (if different)"
          apiUrl="/api/searchabledropdown/currencylist"
          value={formData.p_currency}
          onChange={(p_currency) => updateFormData({ p_currency })}
          placeholder="Select currency..."
          isDisabled={isSaleFlow}
        />
      </div>

      {/* Bank Advice Ref No */}
      <div className="group">
        <TextBox
          label="Bank Advice Ref No"
          placeholder="Enter reference number"
          className="text-sm transition-all duration-200 group-hover:shadow-md"
          value={formData.bankadviserefno}
          onChange={(e) => updateFormData({ bankadviserefno: e.target.value })}
        />
      </div>

      {/* Strike Percentage */}
      <div className="group">
        <TextBox
          label="Strike Percentage"
          placeholder="Enter strike percentage"
          type="number"
          className="text-sm transition-all duration-200 group-hover:shadow-md"
          value={formData.strikepercentage}
          onChange={(e) => updateFormData({ strikepercentage: e.target.value })}
          disabled={isSaleFlow}
        />
      </div>

      {/* Bank */}
      <div className="group flex items-end gap-2 transition-all duration-200 hover:shadow-md hover:shadow-[#428B4D]/10">
        <div className="flex-1">
          <SearchableSelect
            label="Bank"
            apiUrl="/api/searchabledropdown/banklist"
            value={formData.bank}
            onChange={(bank) => updateFormData({ bank })}
            placeholder="Select bank..."
            isDisabled={isSaleFlow}
          />
        </div>
        {!isSaleFlow ? (
          <button
            type="button"
            onClick={() => setShowBankModal(true)}
            className="mb-[2px] h-8 w-8 flex items-center justify-center rounded-md border border-gray-300 hover:border-[#428B4D] hover:bg-[#428B4D]/10 transition"
            title="Add new Bank"
          >
            <Plus className="h-5 w-5 text-[#428B4D]" />
          </button>
        ) : null}
      </div>

      {/* Start Date */}
      <div className="group">
        <DatePicker
          label="Start Date"
          value={formData.startdate}
          onChange={(date: Date) => updateFormData({ startdate: formatDateToString(date) })}
          className="text-sm transition-all duration-200 group-hover:shadow-md"
          disabled={isSaleFlow}
        />
      </div>

      {/* Underlying Options Section */}
      <div className="relative sm:col-span-4 overflow-hidden rounded-lg border border-slate-200 bg-white p-6 shadow-sm transition-all duration-200 hover:shadow-md">
        <div className="relative flex flex-wrap items-center justify-between gap-4 border-b border-slate-200 pb-4 mb-4">
          <div className="space-y-1">
            <p className="text-sm font-semibold uppercase tracking-[0.35em] text-slate-400">
              Underlying Options
            </p>
            <p className="text-xs text-slate-500">
              Capture the full breakdown for each structure leg below.
            </p>
          </div>
          <div className="flex items-center gap-2">
            <span className="inline-flex items-center gap-2 rounded-lg bg-gradient-to-r from-slate-50 to-slate-100 px-3 py-1.5 text-xs font-semibold uppercase tracking-wide text-slate-600 border border-slate-200/60">
              <span className="flex h-5 w-5 items-center justify-center rounded-lg bg-[#428B4D]/10 text-[#428B4D] font-bold">
                {rows.length}
              </span>
              Rows Active
            </span>
            {!isSaleFlow ? (
              <button
                type="button"
                onClick={addUnderlyingRow}
                className="inline-flex items-center gap-1.5 rounded-lg border border-[#428B4D]/40 bg-[#428B4D]/10 px-3 py-1.5 text-xs font-semibold text-[#428B4D] transition hover:bg-[#428B4D] hover:text-white"
              >
                <Plus className="h-3.5 w-3.5" />
                Add Row
              </button>
            ) : null}
          </div>
        </div>

        <div className="relative mt-4 space-y-4">
          {underlyingOptions.map((rowData, index) => (
            <OptionRow
              key={index}
              currencies={currencies}
              rowData={rowData}
              onChange={(updates) => updateUnderlyingOption(index, updates)}
              onAdd={addUnderlyingRow}
              onRemove={() => removeUnderlyingRow(index)}
              canRemove={underlyingOptions.length > 1}
              showAddButton={false}
              isReadOnly={Boolean(isSaleFlow)}
            />
          ))}
        </div>
      </div>
      
      {/* Commission */}
      <div className="group">
        <TextBox
          label="Commission"
          placeholder="Enter commission amount"
          type="number"
          className="text-sm transition-all duration-200 group-hover:shadow-md"
          value={formData.commission}
          onChange={(e) => updateFormData({ commission: e.target.value })}
        />
      </div>
      
      {/* Charges & Fees Abroad */}
      <div className="group">
        <TextBox
          label="Charges and Fees Abroad"
          placeholder="Enter charges amount"
          type="number"
          className="text-sm transition-all duration-200 group-hover:shadow-md"
          value={formData.chargesandfees}
          onChange={(e) => updateFormData({ chargesandfees: e.target.value })}
        />
      </div>

      {/* Federal Turnover Tax */}
      <div className="group">
        <TextBox
          label="Federal Turnover Tax"
          placeholder="Enter tax amount"
          type="number"
          className="text-sm transition-all duration-200 group-hover:shadow-md"
          value={formData.federalturnovertax}
          onChange={(e) => updateFormData({ federalturnovertax: e.target.value })}
        />
      </div>

      {/* Relationship Manager */}
      <div className="group">
        <TextBox
          label="Relationship Manager"
          placeholder="Enter manager name"
          type="text"
          className="text-sm transition-all duration-200 group-hover:shadow-md"
          value={formData.relationshipmanager}
          onChange={(e) => updateFormData({ relationshipmanager: e.target.value })}
        />
      </div>

      {/* Remarks / Comments */}
      <div className="group sm:col-span-4">
        <TextArea
          label="Remarks / Comments"
          placeholder="Enter detailed remarks or comments..."
          value={formData.remarks}
          onChange={(e) => updateFormData({ remarks: e.target.value })}
          rows={4}
          textareaClass="transition-all duration-200 group-hover:shadow-md"
        />
      </div>

      {/* Purpose */}
      <div className="group sm:col-span-4">
        <TextArea
          label="Purpose"
          placeholder="Enter purpose or description..."
          value={formData.description}
          onChange={(e) => updateFormData({ description: e.target.value })}
          rows={4}
          textareaClass="transition-all duration-200 group-hover:shadow-md"
        />
      </div>

      {/* File Upload */}
      <div className="group sm:col-span-4">
        <div className="relative p-6 rounded-lg bg-gradient-to-br from-slate-50/80 to-white border-2 border-dashed border-slate-200 hover:border-[#428B4D]/40 transition-all duration-300">
          {existingFileHref ? (
            <div className="mb-4">
              <a
                href={existingFileHref}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center rounded-lg border border-[#428B4D]/40 bg-white px-3 py-1.5 text-xs font-semibold text-[#428B4D] transition hover:border-[#428B4D] hover:bg-[#428B4D] hover:text-white"
              >
                View Current Document
              </a>
            </div>
          ) : null}
          <FileUploader
            label="Upload Document"
            onFileChange={setSelectedFile}
            maxSizeMB={1}
            allowedTypes={["application/pdf", "image/png", "image/jpg", "image/jpeg"]}
          />
        </div>
      </div>
    </div>
  );
};
